剑指Offer03 逆序输出链表&链表逆序

多写了个逆序链表

 1 /*************************************************************************
 2     > File Name: 03_Pirnt_LinkList.c
 3     > Author: Juntaran
 4     > Mail: JuntaranMail@gmail.com
 5     > Created Time: 2016年08月24日 星期三 02时04分25秒
 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 void ReversePrintList(ListNode* head)
54 {
55     if (head != NULL)
56     {
57         if (head->next != NULL)
58         {
59             ReversePrintList(head->next);
60         }
61         printf("%d ", head->val);
62     }
63 }
64 
65 // 逆序链表
66 ListNode* ReverseList(ListNode* head)
67 {
68     if (head==NULL || head->next==NULL)
69         return head;
70     ListNode* fast = head->next;
71     ListNode* slow = head;
72     slow->next = NULL;
73     ListNode* temp;
74     
75     while (fast->next != NULL)
76     {
77         temp = fast->next;
78         fast->next = slow;
79         slow = fast;
80         fast = temp;
81     }
82     fast->next = slow;
83     return fast;
84 }
85 
86 int main()
87 {
88     ListNode* test = createList();
89     PrintList(test);
90     printf("ReversePrintList:\n");
91     ReversePrintList(test);
92     printf("\n");
93     test = ReverseList(test);
94     PrintList(test);
95     return  0;
96 }

 

posted @ 2016-08-24 02:51  Juntaran  阅读(189)  评论(0编辑  收藏  举报