6-1 单链表逆转 (20分)
题目链接:6-1 单链表逆转 (20分)
方式一:递归逆置单链表
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <math.h> 4 #include <string.h> 5 #include <ctype.h> 6 7 #define maxn 5000 8 #define newline printf("\n") 9 10 11 typedef int ElemType; 12 typedef struct Node *PtrToNode; 13 14 struct Node{ 15 ElemType Data; 16 PtrToNode Next; 17 }; 18 19 typedef PtrToNode List; //定义单链表类型 20 21 22 List Read(); 23 void Print(List L); 24 25 List Reverse(List L); 26 27 28 int main(){ 29 30 List L1,L2; 31 L1 = Read(); 32 L2 = Reverse(L1); 33 Print(L1); 34 Print(L2); 35 return 0; 36 } 37 38 39 List Read(){ 40 41 int n; 42 scanf("%d",&n); 43 int i,temp; 44 List newNode = NULL; 45 List L = (List)malloc(sizeof(struct Node)); //投结点 46 List p = L; 47 if(L!=NULL){ 48 for(i=0;i<n;i++){ 49 scanf("%d",&temp); 50 newNode = (List)malloc(sizeof(struct Node)); 51 newNode->Data = temp; 52 p->Next = newNode; 53 p = p->Next; 54 } 55 p->Next = NULL; 56 } 57 return L->Next; //根据题意推测返回的是不带头结点的单链表 58 59 } 60 61 62 void Print(List L){ 63 List p = L; 64 while(p){ 65 printf("%d",p->Data); 66 p = p->Next; 67 if(p!=NULL){ 68 printf(" "); 69 }else{ 70 printf("\n"); 71 } 72 } 73 74 } 75 76 77 List Reverse(List L){ 78 79 if(L == NULL||L->Next == NULL){ 80 return L; 81 } 82 List head = Reverse(L->Next); 83 L->Next->Next = L; //原来的最后一个结点拼接到新链表的最后一个结点后 84 L->Next = NULL; 85 86 return head; 87 }
方式二:头插法
1 List Reverse(List L){ 2 3 if(L == NULL||L->Next == NULL){ 4 return L; 5 } 6 List p = L->Next; 7 L->Next = NULL; 8 List head = L; 9 List q = NULL; 10 11 while(p){//考察待插入结点p 12 q=p->Next; //记录下一个待插入结点 13 p->Next = head; //连接新链表的首元结点 14 head = p; //成为新链表的新的首元结点 15 p = q; //新的待插入结点 16 } 17 return head; 18 }