LeetCode 206. 【迭代】【递归】反转链表
原题链接
简单
作者:
大明湖的鱼
,
2020-12-31 12:16:24
,
所有人可见
,
阅读 244
迭代实现
/**
* 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 *prev = nullptr;
ListNode * cur = head;
while(cur){
ListNode *temp = cur->next;
cur->next = prev;
prev = cur;
cur = temp;
}
return prev;
}
};
递归实现(太难懂了,手动模拟一下吧)
/**
* 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 *ret = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return ret;
}
};
20220112二刷