给定单链表的头节点 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;
}
};