PROBLEM
剑指 Offer 06. 从尾到头打印链表
难度 简单
MY ANSWER
递归反转链表,然后从末尾往前遍历。时间复杂度O(n),空间复杂度O(n)。
class Solution { public: void reverseNext(ListNode* head) { if(!head->next) { return; } if(head->next->next) { reverseNext(head->next); } head->next->next = head; } vector<int> reversePrint(ListNode* head) { if(!head) { return {}; } ListNode* tmp = head; while(tmp->next) { tmp = tmp->next; } reverseNext(head); head->next = NULL; vector<int> a; while(tmp->next) { a.push_back(tmp->val); tmp = tmp->next; } a.push_back(tmp->val); return a; } };
|
BETTER SOLUTION
调用reverse、栈、递归push_back、迭代反转链表四种。
class Solution { public: vector<int> res; vector<int> reversePrint(ListNode* head) {
ListNode *pre = nullptr; ListNode *next = head; ListNode *cur = head; while(cur){ next = cur->next; cur->next = pre; pre = cur; cur = next; } while(pre){ res.push_back(pre->val); pre = pre->next; } return res; } };
|
SUMMARY
FILO注意栈的使用,与递归有相似之处;可调用reverse反转数组。迭代和递归反转链表稍微改一下就能用于Leetcode 206. 反转链表、剑指 Offer 24. 反转链表、剑指 Offer II 024. 反转链表。
迭代
class Solution { public: ListNode* reverseList(ListNode* head) { ListNode* prev = nullptr; ListNode* curr = head; while (curr) { ListNode* next = curr->next; curr->next = prev; prev = curr; curr = next; } return prev; } };
|
递归
class Solution { public: ListNode* reverseList(ListNode* head) { if (!head || !head->next) { return head; } ListNode* newHead = reverseList(head->next); head->next->next = head; head->next = nullptr; return newHead; } };
|