一、实现思想
1、应该顺着头结点下去,一个一个地反转(而不是从最后一个开始反转)
2、主要用到三个指针,中间的为反转指针,前后两个为辅助记录指针
3、头结点在此的作用就是使代码的通用率变高,不再需要单独处理第一个有效节点
二、图例实现过程
三、实现代码
注意:有很多小细节讲起来会很麻烦,但是认真体会一下就很容易(比如一个条件的控制)
1 #include <stdio.h> 2 #include <stdlib.h> 3 typedef struct teacher 4 { 5 int age; 6 struct teacher *next; 7 } Teacher; 8 //插入 9 Teacher *Insert(Teacher *t, int age) 10 { 11 Teacher *temp = t; 12 if (temp == NULL) 13 return NULL; 14 else 15 while (temp->next != NULL) 16 temp = temp->next; 17 18 Teacher *tNew = (Teacher *)malloc(sizeof(Teacher)); 19 tNew->age = age; 20 tNew->next = NULL; 21 temp->next = tNew; 22 return t; 23 } 24 //打印 25 void Print(Teacher *t) 26 { 27 Teacher *temp = t; 28 if (temp == NULL) 29 { 30 printf("链表为空\n"); 31 return; 32 } 33 while (temp->next != NULL) 34 { 35 temp = temp->next; 36 printf("%d ", temp->age); 37 } 38 } 39 //逆序(主要理解的地方) 40 Teacher *Reverse(Teacher *t) 41 { 42 if (t == NULL) 43 return NULL; 44 Teacher *p, *q, *k; 45 p = t->next; 46 q = p->next; 47 k = q->next; 48 while (q != NULL) 49 { 50 q->next = p; 51 p = q; 52 q = k; 53 if (k != NULL) 54 k = k->next; 55 } 56 t->next->next = NULL; 57 t->next = p; 58 return t; 59 } 60 int main(void) 61 { 62 Teacher *phead = NULL; 63 Teacher tHead; //造一个头结点方便以后的操作 64 tHead.next = NULL; 65 tHead.age = -1; 66 phead = &tHead; 67 for (int i = 0; i < 5; i++) 68 { 69 Insert(phead, i); 70 } 71 Print(phead); 72 printf("\n"); 73 Reverse(phead); 74 Print(phead); 75 return 0; 76 } 77 /* 78 输出 79 ———————————————————————————————————— 80 0 1 2 3 4 81 4 3 2 1 0 82 ———————————————————————————————————— 83 */
(ps:我这里显示了行号,复制也会一同复制过去。你应该会竖直选择然后删除吧)