数据结构之顺序表
这是我写的顺序表,用C语言实现的。
1 #include<stdio.h> 2 #include<stdlib.h> 3 #define ElementType int 4 #define MAXSIZE 100 5 //定义数组结构LNode,其中Last指示数据访问下标,Data存放数据 6 struct LNode{ 7 ElementType Data[MAXSIZE]; 8 int Last; 9 }; 10 typedef struct LNode *List; //定义结构指针List 11 struct LNode L; //定义结构L 12 13 /*下面是函数申明*/ 14 List MakeEmpty(); 15 int Find(ElementType x,List PtrL); 16 void Insert(ElementType x,List PtrL,int i); 17 void Delete(int i,List PtrL); 18 //主函数 19 int main() 20 { 21 List L1 = MakeEmpty(); 22 Insert(10,L1,1); 23 Insert(11,L1,2); 24 Insert(12,L1,3); 25 Insert(13,L1,4); 26 Insert(14,L1,5); 27 int k; 28 for(k=0;k<=L1->Last;k++){ 29 printf("%d %d\n",L1->Data[k],L1->Last); 30 } 31 Delete(2,L1); 32 for(k=0;k<=L1->Last;k++){ 33 printf("%d %d\n",L1->Data[k],L1->Last); 34 } 35 int i = Find(1999,L1); 36 int j = Find(14,L1); 37 printf("%d\n",i); 38 printf("%d",j); 39 return 0; 40 } 41 //建立空表 42 List MakeEmpty() 43 { 44 List PtrL; 45 PtrL=(List)malloc(sizeof(struct LNode)); 46 PtrL->Last = -1; 47 return PtrL; 48 } 49 //在表中查找x,并返回x所在的位置 50 int Find(ElementType x,List PtrL) 51 { 52 int i=0; 53 while(i<=PtrL->Last&&PtrL->Data[i] != x){ 54 i++; 55 } 56 if(i>PtrL->Last){ 57 return -1; 58 } 59 else return i; 60 } 61 /将值x插入n位置处 62 void Insert(ElementType x,List PtrL,int i) 63 { 64 int j; 65 if(PtrL->Last==MAXSIZE-1) 66 { 67 printf("表满!"); 68 return; 69 } 70 if(i<=0 || i>PtrL->Last+2) 71 { 72 printf("插入非法!"); 73 return; 74 } 75 for(j=PtrL->Last+1;j>i-1;j--) //将i到MAXSIZE位置的s所有元素后移一个单位 76 { 77 PtrL->Data[j+1] = PtrL->Data[j]; 78 } 79 PtrL->Data[i-1]=x; 80 PtrL->Last+=1; 81 } 82 //删除表PtrL中第i个元素 83 void Delete(int i,List PtrL) 84 { 85 int j; 86 if(i>PtrL->Last || i<1) 87 { 88 printf("不存在第%d个元素!",i); 89 return; 90 } 91 for(j=i;j<=PtrL->Last;j++) 92 { 93 PtrL->Data[j-1] = PtrL->Data[j]; 94 } 95 PtrL->Last--; 96 return; 97 }Hello World!
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
更多精彩