闲话少说
先给出链表的定义
1 typedef struct Node *PtrToNode; 2 struct Node { 3 ElementType Data; /* 存储结点数据 */ 4 PtrToNode Next; /* 指向下一个结点的指针 */ 5 }; 6 typedef PtrToNode List; /* 定义单链表类型 */
1、链表的逆置
1 List Reverse( List L){ 2 PtrToNode t = NULL; 3 PtrToNode L2 = NULL; 4 while(L!=NULL){ 5 t = L->Next; 6 L->Next = L2; 7 L2 = L; 8 L = t; 9 } 10 return L2; 11 }
2.求链表的长度
1 int Length( List L ) 2 { 3 int length = 0; 4 if (L==NULL) 5 { 6 length = 0; 7 } 8 else 9 { 10 length = 1; 11 while(L->Next ) 12 { 13 L = L->Next; 14 length++; 15 } 16 17 } 18 19 return length; 20 }
3、查找链表中第K个元素
1 ElementType FindKth(List L,int K){ 2 3 while(--K){ 4 if(!L)return ERROR; 5 L=L->Next; 6 7 } 8 if(!L)return ERROR; 9 return L->Data; 10 11 }
4、查找某个元素在链表中第一次出现的位置
1 Position Find( List L, ElementType X ) 2 { 3 //返回线性表中首次出现X的位置。若找不到则返回ERROR 4 List F=L; 5 while(F) 6 { 7 if(F->Data==X) 8 { 9 return F; 10 } 11 12 F=F->Next; 13 } 14 return ERROR; 15 16 }
5、链表的插入
1 List Insert( List L, ElementType X, Position P ) 2 { 3 //将X插入在位置P指向的结点之前,返回链表的表头。如果参数P指向非法位置,则打印“Wrong Position for Insertion”,返回ERROR; 4 List h = L; 5 if( L==P ) 6 { 7 h = (List) malloc(sizeof(struct LNode)); 8 h ->Data = X; 9 h ->Next = P; 10 return h; 11 } 12 while( L ) 13 { 14 if( L->Next == P) 15 { 16 17 break; 18 } 19 L = L->Next; 20 } 21 if(!L) 22 { 23 printf("Wrong Position for Insertion\n"); 24 return ERROR; 25 } 26 L->Next=(List)malloc(sizeof(struct LNode)); 27 L->Next->Data=X; 28 L->Next->Next=P; 29 30 return h; 31 }
6、链表的删除
1 List Delete(List L,Position P) 2 { 3 //将位置P的元素删除并返回链表的表头。若参数P指向非法位置,则打印“Wrong Position for Deletion”并返回ERROR。 4 if(L==P) 5 { 6 L=L->Next; 7 return L; 8 } 9 List head=L; 10 while(L) 11 { 12 if(L->Next==P)break; 13 L=L->Next; 14 } 15 if(!L) 16 { 17 printf("Wrong Position for Deletion\n"); 18 return ERROR; 19 } 20 L->Next=P->Next; 21 free(P); 22 23 return head; 24 }
简单的学生成绩表逆置
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 #define LEN sizeof( struct student) 5 6 typedef struct student *Stu; 7 struct student 8 { 9 int num; 10 int score; 11 Stu next; 12 }; 13 Stu Create() 14 { 15 Stu head,tail,p; 16 int cnt=0; 17 tail = p = ( Stu)malloc(LEN); 18 head=NULL; 19 20 scanf("%d%d",&p->num,&p->score); 21 while( p->num ) 22 { 23 cnt++; 24 if( cnt==1) 25 head = p; 26 else tail->next = p; 27 tail = p; 28 p = (Stu)malloc(LEN); 29 scanf("%d%d",&p->num,&p->score); 30 } 31 tail->next =NULL; 32 return head; 33 } 34 35 Stu Reverse( Stu head) 36 { 37 Stu L=NULL,t=NULL; 38 while( head) 39 { 40 t = head->next; 41 head->next = L; 42 L= head; 43 head=t; 44 } 45 return L; 46 } 47 void print( Stu head) 48 { 49 Stu p; 50 for( p=head; p!=NULL; p=p->next) 51 { 52 printf("%-5d%-5d\n",p->num,p->score); 53 } 54 } 55 56 int main() 57 { 58 Stu L1,L2; 59 L1 = Create(); 60 L2 = Reverse(L1); 61 print( L2 ); 62 return 0; 63 }