leetcode 206.反转链表
题目描述
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
解题思路
该题在python的解法中讲的比较清晰,可以阅读我的这篇博客,下面就直接用cpp代码实现,链表的反转
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = NULL;
ListNode* cur = head;
while (cur){
ListNode* nextNode = cur->next;
cur->next = pre;
pre = cur;
cur = nextNode;
}
return pre;
}
};
递归的反转链表有点复杂,下面结合两张图分析一下,图片来源于12
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
// 是否为空链表、是否递归到尾结点
if(head==NULL || head->next==NULL){
return head;
}
ListNode* newHead = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return newHead;
}
};
欢迎大家关注我的个人公众号,同样的也是和该博客账号一样,专注分享技术问题,我们一起学习进步