首页 > 其他 > 详细

链表反转

时间:2021-01-29 23:54:36      阅读:48      评论:0      收藏:0      [点我收藏+]

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

使用迭代方法,代码如下:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 struct ListNode* reverseList(struct ListNode* head){
 9     if (head == NULL || head->next == NULL)
10         return head;
11     
12     struct ListNode *pre = head;
13     struct ListNode *cur = head->next;
14     struct ListNode *tmp = head->next->next;
15     
16     while(cur)
17     {
18         tmp = cur->next;
19         cur->next = pre;
20         pre = cur;
21         cur = tmp;
22     }
23     head->next = NULL;
24     
25     return pre;
26 
27 }

递归方法如下:

 1 struct ListNode* reverseList(struct ListNode* head){
 2     if (head == NULL || head->next == NULL)
 3         return head;
 4     else
 5     {
 6         struct ListNode *newhead = reverseList(head->next);
 7         head->next->next = head;
 8         head->next = NULL;
 9         return newhead;
10         
11     }
12 }

 

链表反转

原文:https://www.cnblogs.com/ghwxxg/p/14347402.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!