C++
双指针:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* tmpNode;
ListNode* pre = nullptr;
ListNode* cur = head;
while(cur){
tmpNode = cur->next;
cur->next = pre;
pre = cur;
cur = tmpNode;
}
return pre;
}
};
递归
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverse(ListNode* pre, ListNode *cur){
if(cur == nullptr) return pre;
ListNode * tmpNode = cur->next;
cur->next = pre;
return reverse(cur,tmpNode);
}
ListNode* reverseList(ListNode* head) {
return reverse(nullptr, head);
}
};
递归的写法和双指针比较:
return reverse(cur,tmpNode); 就是: // pre = cur; // cur = temp;
// 初始化为 return reverse(nullptr, head);
就是// ListNode* cur = head; // ListNode* pre = NULL;