LeetCode-剑指 Offer 06. 从尾到头打印链表
生活随笔
收集整理的這篇文章主要介紹了
LeetCode-剑指 Offer 06. 从尾到头打印链表
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
劍指 Offer 06. 從尾到頭打印鏈表
思路一:翻轉
1:用vector存從頭到尾的每個節點值
2:返回時候用reverse翻轉一下
時間復雜度:O(n)
空間復雜度:O(n)
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/ class Solution { public:vector<int> reversePrint(ListNode* head) {vector<int> vec;while(head!=nullptr){vec.push_back(head->val);head = head->next;}reverse(vec.begin(), vec.end());return vec;} };思路二:遞歸
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/ class Solution { public:vector<int> res;vector<int> reversePrint(ListNode* head) {if(head==nullptr) return res;reversePrint(head->next);//遞歸到最后一層res.push_back(head->val);//開始從最后壓入值到容器return res;} };思路三:使用輔助棧
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/ class Solution { public:vector<int> reversePrint(ListNode* head) {stack<ListNode*> stk;vector<int> res;while(head!=nullptr){stk.push(head);head = head->next;}while(!stk.empty()){int tempnum = stk.top()->val;stk.pop();res.push_back(tempnum);}return res;} };總結
以上是生活随笔為你收集整理的LeetCode-剑指 Offer 06. 从尾到头打印链表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode-剑指 Offer 12
- 下一篇: LeetCode-剑指 Offer 25