1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
| #include<stdio.h> #include<malloc.h> typedef int ElementType; typedef struct LNode *List; struct LNode{ ElementType Data; List Next; }; List L;
List MakeEmpty(); int Length(List L); List FindKth(int K,List L); List Find(ElementType X,List L); List Insert(ElementType X,int i,List L); List Delete(int i,List L); void Print(List L);
List MakeEmpty(){ List L = (List)malloc(sizeof(struct LNode)); L = NULL; return L; }
int Length(List L){ List p = L; int len=0; while(p){ p = p->Next; len++; } return len; }
List FindKth(int K,List L){ List p = L; int i = 1; while(p && i<K){ p = p->Next; i++; } if(i == K) return p; else return NULL; }
List Find(ElementType X,List L){ List p = L; while(p && p->Data!=X) p = p->Next; return p; }
List Insert(ElementType X,int i,List L){ List p,s; if(i == 1){ s = (List)malloc(sizeof(struct LNode)); s->Data = X; s->Next = L; return s; } p = FindKth(i-1,L); if(!p){ printf("结点错误"); return NULL; }else{ s = (List)malloc(sizeof(struct LNode)); s->Data = X; s->Next = p->Next; p->Next = s; return L; } }
List Delete(int i,List L){ List p,s; if(i==1){ s = L; if(L) L = L->Next; else return NULL; free(s); return L; } p = FindKth(i-1,L); if(!p || !(p->Next)){ printf("结点错误"); return NULL; }else{ s = p->Next; p->Next = s->Next; free(s); return L; } }
void Print(List L){ List t; int flag = 1; printf("当前链表为:"); for(t = L;t;t =t->Next){ printf("%d ",t->Data); flag = 0; } if(flag) printf("NULL"); printf("\n"); }
int main(){ L = MakeEmpty(); Print(L); L = Insert(11,1,L); L = Insert(25,1,L); L = Insert(33,2,L); L = Insert(77,3,L); Print(L); printf("当前链表长度为:%d\n",Length(L)); printf("此时链表中第二个结点的值是:%d\n",FindKth(2,L)->Data); printf("查找22是否在该链表中:"); if(Find(22,L)) printf("是!\n"); else printf("否!\n"); printf("查找33是否在该链表中:"); if(Find(33,L)) printf("是!\n"); else printf("否!\n"); L = Delete(1,L); L = Delete(3,L); printf("----------删除后-----\n"); Print(L); return 0; }
|