版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014485485/article/details/81950195
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
反转链表,有两种方式:迭代和递归
方法1:迭代
思路:用三个辅助指针,从头结点开始遍历反向,最后加上空结点
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
//Iterative
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL)
return head;
ListNode *p1, *p2, *p3;
p1 = head, p2 = head->next;
while (p2)
{
p3 = p2->next;
p2->next = p1;//转向
p1 = p2;//前进
p2 = p3;
}
head->next = NULL;
head = p1;
return head;
}
};
方法2:递归
思路:找到最后一个结点,反向,后面有序了就断链不用排了,进入下一次递归。
附上一位印度小哥的图解:https://www.youtube.com/watch?v=KYH83T4q6Vs
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL)
return head;
ListNode *p = head;
head = reverseList(p->next);
p->next->next = p;//反向
p->next = NULL;//unlink
return head;
}
};
扫描二维码关注公众号,回复:
3086813 查看本文章