Leetcode 206. Reverse Linked List
题目
解法:recursive和iterative
python版recursive解法:
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
def reverse(head,prev):
if not head:
return prev
_next = head.next
head.next = prev
return reverse(_next,head)
return reverse(head,None)
C++版iterative
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *prev = nullptr;
ListNode *curr = head;
while (curr){
ListNode* temp = curr->next;
curr->next = prev;
prev = curr;
curr = temp;
}
return prev;
}
};