线性表和堆栈的一些C语言代码
这些代码出自慕课浙江大学的《数据结构》
线性表数组实现:
1 #include<stdio.h> 2 #define MAXSIZE 100 3 #include<stdlib.h> 4 #include<malloc.h> 5 6 //define linkear list 7 typedef struct lNode{ 8 int data[MAXSIZE]; 9 int length; 10 }list,*pList; 11 12 //initalize a linkear list 13 pList init(){ 14 pList li; 15 li = (pList)malloc(sizeof(list)); 16 if(li){ 17 li->length=0; 18 } 19 return (li); 20 } 21 22 //find element by index 23 int findKth(int index,pList li){ 24 return li->data[index]; 25 } 26 27 //inde element by key 28 int findElement(int key,pList li){ 29 pList head = li; 30 int i=0; 31 while(li->data[i]!=key && i <= li->length){ 32 i++; 33 } 34 if(i>li->length){ 35 return -1; 36 }else{ 37 return i; 38 } 39 } 40 41 int insert(int key,pList li,int index){ 42 int i; 43 if(li->length==MAXSIZE){ 44 printf("linker has filled,don't insert to it"); 45 return 0; 46 } 47 if(index>li->length){ 48 printf("the index greater than table length!"); 49 } 50 for(i=li->length-1;i>=index;i--){ 51 li->data[i+1]=li->data[i]; 52 } 53 li->data[index]=key; 54 li->length++; 55 return 1; 56 } 57 58 int insertAfter(int key,pList li){ 59 if(li->length==MAXSIZE){ 60 printf("linker has filled,don't insert to it"); 61 return 0; 62 } 63 //li->length++; 64 li->data[li->length]=key; 65 li->length++; 66 return 1; 67 } 68 69 //delete the index element 70 int deleteElementByIndex(pList li,int index){ 71 int i; 72 if(li->length==0){ 73 printf("The table has be empty,don't delete any element!"); 74 return 0; 75 } 76 for(i=index+1;i<=li->length;i++){ 77 li->data[i-1]=li->data[i]; 78 } 79 li->length--; 80 } 81 82 void toString(pList li){ 83 int i; 84 if(li->length==0){ 85 printf("The table has be empty"); 86 return; 87 } 88 printf("toString: "); 89 for(i=0;i<li->length;i++){ 90 printf("%d ",li->data[i]); 91 } 92 printf("\n"); 93 } 94 95 void main(){ 96 int Kth = 2; 97 int keyEle = 13; 98 pList pli = init(); 99 insertAfter(12,pli); 100 insertAfter(13,pli); 101 insert(14,pli,1); 102 //deleteElementByIndex(pli,0); 103 toString(pli); 104 int key = findKth(1,pli); 105 printf("the %d th is %d\n",Kth,key); 106 int index = findElement(keyEle,pli); 107 printf("the %d element's index is %d",keyEle,index); 108 }