反转链表
carl原文:反转链表
206.反转链表
//双指针法:pre:前一个 cur:当前 next:下一个
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = nullptr;
ListNode* cur = head;
while(cur){
ListNode* next = cur ->next;
cur -> next = pre;
pre = cur;
cur = next;
}
return pre;
}
};
//方法二:栈
class Solution {
public:
ListNode* reverseList(ListNode* head) {
stack<ListNode*>st;
while(head != nullptr) { //进栈
st.push(head);
head = head -> next;
}
if(st.empty())return nullptr; //判断是否为空
ListNode* node = st.top();
ListNode* res = node;
while(!st.empty()){ //出栈
ListNode* temp = st.top();
node -> next = temp;
node = node -> next;
st.pop();
}
node -> next = nullptr; //末尾指向空
return res;
}
};
//方法三:递归
//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* newh = reverseList(head -> next);
head -> next -> next = head;
head -> next = nullptr; //断开防止循环
return newh;
}
};
递归难点: