剑指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 }

 

转载于:https://www.cnblogs.com/Juntaran/p/5801417.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值