1 /*************************************************************************
2 > File Name: 14_ReverseListNode.cpp
3 > Author: Juntaran
4 > Mail: JuntaranMail@gmail.com
5 > Created Time: 2016年08月30日 星期二 15时47分32秒
6 ************************************************************************/
7
8 #include <stdio.h>
9 #include <malloc.h>
10
11 // 链表结构体
12 struct ListNode
13 {
14 int val;
15 struct ListNode* next;
16 };
17
18 // 构造链表
19 ListNode* createList()
20 {
21 struct ListNode* head;
22 struct ListNode* p;
23 struct ListNode* q;
24 head = p = (ListNode*)malloc(sizeof(ListNode));
25 head->val = 0;
26 for (int i = 1; i <= 10; ++i)
27 {
28 q = (ListNode*)malloc(sizeof(ListNode));
29 q->val = i;
30 p->next = q;
31 p = q;
32 }
33 p->next = NULL;
34 return head;
35 }
36
37 // 顺序输出链表
38 void PrintList(ListNode* head)
39 {
40 if (head == NULL)
41 return;
42 ListNode* temp = head;
43 printf("PrintList:\n");
44 while (temp != NULL)
45 {
46 printf("%d ", temp->val);
47 temp = temp->next;
48 }
49 printf("\n");
50 }
51
52 // 逆序链表
53 ListNode* ReverseList(ListNode* head)
54 {
55 if (head==NULL || head->next==NULL)
56 return head;
57 ListNode* fast = head->next;
58 ListNode* slow = head;
59 slow->next = NULL;
60 ListNode* temp;
61
62 while (fast->next != NULL)
63 {
64 temp = fast->next;
65 fast->next = slow;
66 slow = fast;
67 fast = temp;
68 }
69 fast->next = slow;
70 return fast;
71 }
72
73 int main()
74 {
75 ListNode* test = createList();
76 PrintList(test);
77 test = ReverseList(test);
78 PrintList(test);
79 return 0;
80 }