第一句子网 - 唯美句子、句子迷、好句子大全
第一句子网 > C语言实现建立顺序表 修改顺序表 插入顺序表 删除顺序表

C语言实现建立顺序表 修改顺序表 插入顺序表 删除顺序表

时间:2021-01-18 06:53:53

相关推荐

C语言实现建立顺序表 修改顺序表 插入顺序表 删除顺序表

#include <stdio.h>#include <stdlib.h>#define OK 1#define ERROR 0#define OVERFLOW -2#define LIST_INIT_SIZE 100#define LISTINCREMENT 10typedef int Elemtype;typedef int Status;Elemtype *newbase,*p,*q;//顺序表的结构描述 struct sequence_list{Elemtype *elem;int length;//顺序表元素个数 int listsize;//顺序表的长度 };typedef struct sequence_list Sqlist;//顺序表的初始化 Status Initlist_Sq(Sqlist &L){//构造一个空的线性表 L.elem=(Elemtype*)malloc(LIST_INIT_SIZE*sizeof(Elemtype));if(!L.elem)//分配空间失败 exit(OVERFLOW);L.length=0;//空表长度为0L.listsize=LIST_INIT_SIZE;//初始储存容量 return OK; }//Initlist_Sq//顺序表的建立void creat_list(Sqlist &L){int n,i;printf("请输入顺序表元素的个数:");scanf("%d",&n);for(i=0;i<n;i++){printf("请输入第%d个元素:",i+1);scanf("%d",&(L.elem[i]));L.length++;} } //顺序表的打印void printf_list(Sqlist &L){int i;printf("输出该顺序表:"); for(i=0;i<L.length;i++){printf(" %d ",L.elem[i]);}} //顺序表的插入Status ListInsert_Sq(Sqlist &L,int place,Elemtype temp){if(place<1||place>L.length+1){printf("插入位置错误"); return ERROR;} if(L.length>=L.listsize){newbase=(Elemtype*)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(Elemtype));if(!newbase)exit(ERROR);L.listsize+=LISTINCREMENT; }q=&(L.elem[place-1]);for(p=&(L.elem[L.length-1]);p>=q;--p){*(p+1)=*p;}*q=temp;++L.length;return OK;}//顺序表的删除Status List_Del(Sqlist &L,int place){if(place<1||place>L.length){printf("非法位置\n");return ERROR;}q=&(L.elem[L.length-1]);for(p=&(L.elem[place-1]);p<=q;p++){*p=*(p+1);}L.length--;return OK; } //顺序表的修改Status ListUpdate_Sq(Sqlist &L,int place,int nuwdata){if(place<1||place>L.length){printf("非法位置\n");return ERROR;}L.elem[place-1]=nuwdata;return OK;}int main(){int place,num,i;Sqlist L;Initlist_Sq (L);creat_list (L);printf("\n");printf_list (L);printf("\n增删查改操作");printf("\n1.插入 2.节点删除 3.修改\n");while(1){printf("请输入要执行的编号\n");scanf("%d",&num);if(num>=1&&num<=3){break;}elseprintf("非法输入\n");}switch(num){case 1:{printf("请输入要插入的位置:\n");scanf("%d",&place);printf("请输入要插入的数:\n");scanf("%d",&num);ListInsert_Sq(L,place,num);}break;case 2:{printf("请输入要删除节点位置:\n");scanf("%d",&place);List_Del(L,place);}break;case 3:{printf("请输入要修改的节点的位置:\n");scanf("%d",&place);printf("请输入修改成的数:\n");scanf("%d",&num);ListUpdate_Sq(L,place,num);}break;}printf_list (L);printf("\n");return 0;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。