顺序表的基本操作【c语言】【创建、插入、删除、输出】
作为数据结构初学者,上课时对一些知识点掌握得不是很透彻,所以利用课余时间通过微博平台总结所学知识,加深对知识的见解,记录学习历程便于后需要时参考。
1 #include<stdio.h> 2 #include<malloc.h> 3 #define OK 1 4 #define ERROR 0 5 #define LIST_INIT_SIZE 100 6 #define LISTINCREMENT 10 7 #define ElemType int
顺序表的基本操作之结构体的创建:
1 typedef struct 2 { 3 int *elem;//存储空间基址,也就是该数据得到的内存分配的起始地址 4 int length;//当前长度 5 int listsize;//当前分配的存储容量 6 } SqList;
构造一个空的线性表:
int InitList_Sq(SqList &L) //&此符号不是c语言里的取地址符号,而是C++里的引用符号,用法为为主函数里的T,取一个别名,这样子对L操作即相当于对T操作 { // 该线性表预定义大小为LIST_INIT_SIZE L.elem=(ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType)); //ElemType即为int if(!L.elem) return 0;//malloc返回值为void*,void* 类型可以强制转换为任何其它类型的指针,在这里L.elem为非零。 L.length=0; L.listsize=LIST_INIT_SIZE;//LIST_INIT_SIZE=100 return OK; }
在顺序线性表L中第i个位置之前插入新的元素e:
1 int ListInsert_Sq(SqList &L,int i,int e) 2 { 3 int *newbase;//声明整型指针变量 4 int *q,*p; 5 if(i<1||i>L.length+1) return ERROR;//判断i值是否合法,1<i<L.length+1 6 if(L.length>=L.listsize)//判断当前长度是否大于当前的存储容量,如果大于,则增加LISTINCREMENT长度,即10 7 { 8 newbase=(ElemType*)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(ElemType)); 9 if(!newbase) return 0; 10 L.elem=newbase; 11 L.listsize+=LISTINCREMENT; 12 } 13 q=&(L.elem[i-1]);//把插入位置的地址赋值给q 14 for(p=&(L.elem[L.length-1]); p>=q; p--) 15 *(p+1)=*p;//把i后面的元素都向后移一位 16 *q=e;//在i位置插入e 17 ++L.length;//长度增加 18 return OK; 19 }
在顺序线性表L中删除第i个位置的元素,并用e返回其值:
int ListDelete_Sq(SqList &L,int i, int &e) { // i的合法值为1≤i≤L.length int *p; int *q; if(i<1||i>L.length) return ERROR; p=&(L.elem[i-1]);//把i位置的地址赋值给p e=*p;//把i位置的值赋值给e q=L.elem+L.length-1; for(++p; p<=q; ++p) *(p-1)=*p;//i后面的元素向前移一位,直接覆盖i位置的值 --L.length;//长度减少 return OK; }
顺序表基本操作之输出:
int Load_Sq(SqList &L) { // 输出顺序表中的所有元素 int i; if(L.length==0) printf("The List is empty!"); else { printf("The List is: "); for( i=0; i<L.length; i++) printf("%d ",L.elem[i]); // 请填空 } printf("\n"); return OK; }
下面是主函数:
1 int main() 2 { 3 SqList T; 4 int a, i; 5 ElemType e, x; 6 if(InitList_Sq(T)) // 判断顺序表是否创建成功 7 { 8 printf("A Sequence List Has Created.\n"); 9 } 10 while(1) 11 { 12 printf("1:Insert element\n2:Delete element\n3:Load all elements\n0:Exit\nPlease choose:\n"); 13 scanf("%d",&a); 14 switch(a) 15 { 16 case 1: 17 scanf("%d%d",&i,&x); 18 if(!ListInsert_Sq(T,i,x)) printf("Insert Error!\n"); // 判断i值是否合法 19 else printf("The Element %d is Successfully Inserted!\n", x); 20 break; 21 case 2: 22 scanf("%d",&i); 23 if(!ListDelete_Sq(T,i,e)) printf("Delete Error!\n"); // 判断i值是否合法 24 else printf("The Element %d is Successfully Deleted!\n", e); 25 break; 26 case 3: 27 Load_Sq(T); 28 break; 29 case 0: 30 return 1; 31 } 32 } 33 }