力扣刷题日记24---剑指 Offer II 024. 反转链表
给定单链表的头节点 head ,请反转链表,并返回反转后的链表的头节点。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
提示:
链表中节点的数目范围是 [0, 5000]
-5000 <= Node.val <= 5000
进阶:链表可以选用迭代或递归方式完成反转。你能否用两种方法解决这道题?
思路1:三指针(迭代)
思路如下:初始化三个指针,第一个为前驱节点 pre,指向 nullptr; 第二个为当前节点 cur,指向 head;第三个为下个节点 next,指向 head->next。然后开始反转过程,即 cur 的下个节点该为指向前一个节点,然后后移前驱结点 pre 、当前节点 cur 和 下个节点 next。循环至 next 指向空指针,即达到链表的结尾。此时 cur 指向链表的最后一个节点,pre 指向最后一个节点的前一个节点,将 cur 下个节点指向 pre 后反转完成。反转后链表的头结点即为 cur。脑补不出来的可以在纸上模拟以下,链表题在纸上一画清晰明了。
代码如下:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == nullptr || head->next == nullptr)
return head;
ListNode* pre = nullptr, * cur = head, * next = head->next;
while(next){
cur->next = pre;
pre = cur;
cur = next;
next = next->next;
}
cur->next = pre;
return cur;
}
};
时间复杂度:O(n);空间复杂度:O(1)。
思路2:递归
代码如下:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == nullptr || head->next == nullptr)
return head;
ListNode* newHead = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return newHead;
}
};
时间复杂度:O(n);空间复杂度:O(n)。
之前看过一篇讲解递归的文章,供大家参考:递归反转链表.
这里还有和视频讲解:视频讲解.
思路3:栈
思路如下:首先遍历链表,并将链表的每个节点都存入栈中。然后依次取出栈顶的元素,作为新链表的 next 节点。取出栈中所有元素后,链表反转完成。
代码如下:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == nullptr || head->next == nullptr)
return head;
stack<ListNode*> st;
ListNode* cur = head;
while(cur){
st.push(cur);
cur = cur->next;
}
ListNode* newHead = st.top();
st.pop();
cur = newHead;
while(!st.empty()){
cur->next = st.top();
cur = cur->next;
st.pop();
}
cur->next = nullptr;
return newHead;
}
};
时间复杂度:O(2 * n);空间复杂度:O(n)。