顺序表的基本操作【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 {
3int *elem;//存储空间基址,也就是该数据得到的内存分配的起始地址
4int length;//当前长度
5int 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) return0;//malloc返回值为void*,void* 类型可以强制转换为任何其它类型的指针,在这⾥L.elem为⾮零。
L.length=0;
L.listsize=LIST_INIT_SIZE;//LIST_INIT_SIZE=100
return OK;
}
在顺序线性表L中第i个位置之前插⼊新的元素e:
1int ListInsert_Sq(SqList &L,int i,int e)
2 {
3int *newbase;//声明整型指针变量
4int *q,*p;
5if(i<1||i>L.length+1) return ERROR;//判断i值是否合法,1<i<L.length+1
6if(L.length>=L.listsize)//判断当前长度是否⼤于当前的存储容量,如果⼤于,则增加LISTINCREMENT长度,即10
7    {
8        newbase=(ElemType*)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(ElemType));
9if(!newbase) return0;
10        L.elem=newbase;
11        L.listsize+=LISTINCREMENT;
12    }
13    q=&(L.elem[i-1]);//把插⼊位置的地址赋值给q
14for(p=&(L.elem[L.length-1]); p>=q; p--)
15        *(p+1)=*p;//把i后⾯的元素都向后移⼀位
16    *q=e;//在i位置插⼊e
17    ++L.length;//长度增加
18return 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;
}
下⾯是主函数:
1int main()
2 {
3    SqList T;
4int a, i;
5    ElemType e, x;
6if(InitList_Sq(T))  // 判断顺序表是否创建成功
7    {
8        printf("A Sequence List Has Created.\n");
9    }
10while(1)
11    {
12        printf("1:Insert element\n2:Delete element\n3:Load all elements\n0:Exit\nPlease choose:\n");
13        scanf("%d",&a);
14switch(a)
15        {
16case1:
17            scanf("%d%d",&i,&x);
18if(!ListInsert_Sq(T,i,x)) printf("Insert Error!\n"); // 判断i值是否合法
19else printf("The Element %d is Successfully Inserted!\n", x);
20break;
21case2:
22            scanf("%d",&i);
23if(!ListDelete_Sq(T,i,e)) printf("Delete Error!\n"); // 判断i值是否合法
24else printf("The Element %d is Successfully Deleted!\n", e);
25break;
26case3:
27            Load_Sq(T);
28break;
29case0:c语言listinsert函数
30return1;
31        }
32    }
33 }

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。