206.反转链表
难度:简单
我写的:(妖魔化双指针,做的时候画图就好)
class Solution {
public:
ListNode* temp;
ListNode* reverseList(ListNode* head) {
if(!head || !head->next) return head;
ListNode* now = head -> next;
ListNode* last = head;
while(head -> next){
head -> next = now -> next;
now -> next = last;
last = now;
now = head -> next;
}
return last;
}
};
递归写法:
https://leetcode-cn.com/problems/reverse-linked-list/solution/dong-hua-yan-shi-206-fan-zhuan-lian-biao-by-user74/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head || !head->next) return head;
ListNode* temp = reverseList(head->next);//函数栈里的临时变量
head -> next -> next = head;
head -> next = NULL;
return temp;//每次函数栈中的temp不变 都是最后一个元素,忘记就回顾链接里的ppt
}
};
要多加强函数栈学习5555555