1. 反转链表
206
题目: 给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
思路:改变链表指针的指向,不用重新创建一个链表,浪费内存。 双指针法,递归法(与双指针一样,除了不用更新两个指针向前走)
笔记: C++: 从后往前迭代有点想不通,抓住: 迭代函数return的是新链表的head,迭代函数调用时按从前往后的顺序不断给他喂。
C++:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* p = head;
ListNode* pre = nullptr;
ListNode* tmp;
while(p){
tmp = p->next;
p->next = pre;
pre = p;
p = tmp;
}
return pre;
}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
return reverse(nullptr, head);
}
ListNode* reverse(ListNode* pre, ListNode* p){
if(p == nullptr) return pre;
ListNode* tmp = p->next;
p->next = pre;
return reverse(p, tmp);
}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL) return NULL;
if(head->next == NULL) return head;
ListNode* last = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return last;
}
};
Python:
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
p = head
pre = None
while(p!=None):
tmp = p.next
p.next = pre
pre = p
p = tmp
return pre
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
def reverse(pre, p):
if not p:
return pre
tmp = p.next
p.next = pre
return reverse(p, tmp)
return reverse(None, head)
|