标签:des style io strong 数据 for amp size
顺序线性表:
#include<stdio.h> #include<stdlib.h> #include<malloc.h> typedef int ElemType; //声明新类型名 typedef struct List { ElemType * elem; int length; int maxsize; }Sqlist; void Init_Sqlist(Sqlist &L) // 构造空线性表 { L.elem = (ElemType *)malloc(100 * sizeof(ElemType)); if(!L.elem) exit(-1); L.maxsize = 100; L.length = 0; } void DestroyList(Sqlist &L) // 销毁线性表 { if(L.elem) free(L.elem); } int GetLength(Sqlist L) { return (L.length); } void GetElem(Sqlist L,int i,ElemType &e) // 用e返回L中第i个元素的值 { if(i<0 || i>L.length) e = -1; e = L.elem[i-1]; } void SqlistInsert(Sqlist &L,int i,ElemType e) // 插入 在L中第i个位置之前插入新的元素e,L的长度加1 { int j; if(i<1 ||i>L.length+1) exit(-1); if(L.length >= L.maxsize){ L.elem = (ElemType * ) realloc (L.elem, (10 + 100)* sizeof(ElemType)); if(!L.elem) exit(-1); L.maxsize += 10; } for(j = L.length;j>=i-1;j--) { L.elem[j+1] = L.elem[j]; } L.elem[j+1] = e; L.length += 1; } void SqlistDelete (Sqlist &L,int i,ElemType &e) // 删除 在L中删除出第i个数据元素,并用e返回其值,L的长度减1 { int j; if((i<1)||(i>L.length)) exit(-1); if(L.length>L.maxsize) { L.elem=(ElemType *) realloc (L.elem,10*sizeof(ElenType)); if(!L.elem) exit(-1); L.maxsize+=10; } for(j=L.length;j<=i-1;j--) { L.elem[j-1]=L.elem[j]; } L.elem[j+1]=e; L.length -= 1; } void PrintSqList(Sqlist L) //输出链表 { int i; for(i = 0;i<L.length;i++) { printf("%d ",L.elem[i]); } } int main() { Sqlist L; int e; Init_Sqlist(L); int i; for(i = 1;i<=5;i++) { scanf("%d",&e); SqlistInsert(L,i,e); } PrintSqList(L); return 0; }
链式线性表:
#include<stdio.h> #include<stdlib.h> #include<malloc.h> typedef int ElemType; typedef struct Node{ ElemType data; struct Node * next; }* Linklist; void InitLinklist (Linklist &L){ L = NULL; } void LinklistInsert1 (Linklist &L ,ElemType e) //插入在链表的开头 (L为头指针) { Linklist s ; s = (Linklist) malloc (sizeof(struct Node)); s->data = e; s->next = L; L = s; } void LinklistInsert2 (Linklist &L,int i,ElemType e){ Linklist p=L ; int j = 0; while(p && j<i-1){ p = p->next; j++; } if(!p|| j>i-1){ Linklist s = (Linklist) malloc (sizeof(struct Node)); s->data = e; s->next = p->next; p->next = s; } } void LinklistDelete(Linklist &L,int i,ElemType &e){ int j=0; Linklist p, q; p = L; while(p->next && j<i-1){ p = p->next; j++; } if(! (p->next) || j>i-1){ q = p->next; p->next=q->next; // 或者 p->next=p->next->next e = q->data; free(q); } } void PrintLinklist(Linklist L){ Linklist p; p = L; while(p){ printf("%d ",p->data); p = p->next; } } void LinklistFind(Linklist L,int i,ElemType &e){ int j=0; Linklist p=L; while(p && j<i-1){ p=p->next; j++; } if(p && i>=0){ e = p->data; } else e = -1; } int main(){ int i; int e; Linklist L; InitLinklist(L); for(i=1;i<=4;i++){ LinklistInsert( L,i); } LinklistFind(L,1,e); printf("%d\n",e); LinklistDelete(L,3,e); printf("%d\n",e); PrintLinklist(L); LinklistInsert2(L,2,2); PrintLinklist(L); return 0; }
标签:des style io strong 数据 for amp size
原文地址:http://blog.csdn.net/fyxz1314/article/details/38467059