给定单链表的头节点 head ,请反转链表,并返回反转后的链表的头节点。

解法1:使用辅助栈,注意链表以空结尾;时间复杂度空间复杂度O(N)
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == nullptr) return head;
ListNode* rhead = new ListNode(-1);
ListNode* ahead = rhead;
stack<ListNode*> rstack;
while(head){
rstack.push(head);
head = head->next;
}
while(!rstack.empty()){
//ahead->next = rstack.top();
ahead->next = rstack.top();
ahead = ahead->next;
rstack.pop();
}
ahead->next = nullptr;
return rhead->next;
}
};
解法二:迭代法 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == nullptr){
return head;
}
ListNode* pre = nullptr;
ListNode* cur = head;
while(cur!=nullptr){
ListNode* temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
};
链表反转算法
本文介绍两种链表反转的方法:一种是使用辅助栈实现,时间复杂度和空间复杂度均为O(N);另一种是通过迭代法实现,时间复杂度为O(n),空间复杂度为O(1)。
158

被折叠的 条评论
为什么被折叠?



