反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
使用两种方法,代码如下:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #define ELTYPE int 4 5 typedef struct node { 6 ELTYPE m; 7 struct node *next; 8 } *NODE; 9 10 //方法一:就地反转 11 void InversionNode(NODE head) { 12 NODE p,t,q; 13 p = NULL; 14 t = head->next; 15 q = t->next; 16 if(t == NULL || q == NULL) return; // 空表和仅有一个结点的链表不用倒置 17 18 t->next = NULL; 19 while(q) { 20 21 p = q->next;// 前进一个结点 22 q->next = t;// 倒置结点 23 t = q; 24 q = p; // p指向新倒置的结点 25 26 } 27 28 head->next = t; // head指向倒置后的链表 29 } 30 31 32 33 //方法二:头节点插入 34 void insertNode(NODE head) 35 { 36 NODE p,t,q; 37 q = NULL; 38 t = head->next; 39 p = t->next; 40 41 if(t == NULL || p ==NULL){ 42 printf("hello world"); 43 return; 44 } 45 t->next = NULL; 46 47 while(p){ 48 head->next = p; 49 q = p->next; 50 p ->next = t; 51 t = p; 52 p = q; 53 } 54 55 } 56 57 //打印链表 58 void ShowNode(NODE head) { 59 NODE p = head->next; 60 for(;p;p = p->next) printf("%d ",p->m); 61 printf(" "); 62 } 63 // 创建有头结点的单向链表 64 NODE CreatNode(int n) { 65 int i; 66 NODE head,p,q; 67 head = p = (NODE)malloc(sizeof(NODE)); 68 for(i = 0; i < n; ++i) { 69 q = (NODE)malloc(sizeof(NODE)); 70 q->m = 2 * i; 71 p->next = q; 72 p = q; 73 } 74 p->next = NULL; 75 return head; 76 } 77 int main() { 78 NODE head = CreatNode(5); 79 ShowNode(head); 80 InversionNode(head); 81 ShowNode(head); 82 return 0; 83 }
运行结果:
0 2 4 6 8
8 6 4 2 0