反轉一個單鏈表。
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
進階:
你可以迭代或遞歸地反轉鏈表。你能否用兩種方法解決這道題?
解法一:
逆序可以考慮堆棧,先遍歷整個鏈表,並同時把元素進堆棧,然後出來構造出新的鏈表即反轉後的鏈表,時間複雜度,空間複雜度。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == nullptr || head -> next == nullptr) {
return head;
}
stack<ListNode*> nodes;
while (head != nullptr) {
nodes.push(head);
head = head -> next;
}
head = nodes.top();
nodes.pop();
ListNode* temp = head;
while (!nodes.empty()) {
ListNode* node = nodes.top();
nodes.pop();
temp -> next = node;
temp = node;
}
temp -> next = nullptr;
return head;
}
};
解法二:
解法一利用了堆棧,空間複雜度爲,爲了進一步優化空間複雜度,進行原地反轉,新定義兩個輔助指針即可解決該問題。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == nullptr || head -> next == nullptr) {
return head;
}
ListNode *p1 = head -> next, *p2 = nullptr;
head -> next = nullptr;
p2 = p1 -> next;
p1 -> next = head;
head = p2;
while (head != nullptr) {
p2 = head -> next;
head -> next = p1;
p1 = head;
head = p2;
}
return p1;
}
};
解法三:
解法一用了堆棧思想,任何遞歸問題可轉化爲迭代問題,但迭代問題不一定可以轉化爲遞歸解決,想了想,函數調用本就是棧的規律,可以採取遞歸解決該問題。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head, ListNode* pre = nullptr) {
if (head == nullptr) {
return head;
}
if (head -> next == nullptr) {
head -> next = pre;
return head;
}
ListNode *tmp = head -> next;
head -> next = pre;
return reverseList(tmp, head);
}
};