劍指offer 從尾到頭打印鏈表

題目描述

輸入一個鏈表,從尾到頭打印鏈表每個節點的值。

思路

總共有五種方法,如下:

  1. 將原鏈表的值存在一個棧中,然后再將棧輸出到另一個vector數組里。
  2. 直接將原鏈表的值存在一個vector數組里,最后reverse翻轉一下。
  3. 每插入一個,都放到最前面,復雜度是$n^{2}$,不是很高效。
  4. 通過遞歸到最后一個值,再一層一層輸入到vector數組里。
  5. 直接將鏈表翻轉。

代碼

class Solution {
public:
  vector<int>printListFromTailToHead(ListNode*head) {
        int digit;
        stack<int> f;
        vector<int> res;
        ListNode *t = head;
        while(t != NULL)
        {
            f.push(t->val);
            t = t->next;
        }
        while(!f.empty())
        {
            digit = f.top();
            f.pop();
            res.push_back(digit);
        }
        return res;
    }
};
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> res;
        while(head != NULL)
        {
            res.push_back(head->val);
            head = head->next;
        }
        reverse(res.begin(),res.end());
        return res;
    }
};

class Solution {
public:
    vector<int> printListFromTailToHead(struct ListNode* head) {
        vector<int> res;
        if(head != NULL)
        {
            while(head != NULL)
            {    
               res.insert(res.begin(),head->val);
               head = head->next;
            }                      
        }
        return res;
    }
};
class Solution {
public:
    vector<int> res;
    vector<int> printListFromTailToHead(ListNode* head) {
        if(head!=NULL){
            printListFromTailToHead(head->next);
            res.push_back(head->val);
        }
        return res;
    }
};
class Solution {
public:
   vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> res;
        ListNode *pre = NULL;
        ListNode *p = NULL;
        while(head != NULL)
        {
            p = head->next; //p為head的下一個節點
            head->next = pre;//指向前一個節點
            pre = head;//向后移動
            head = p;//向后移動
        }
        while(pre != NULL)
        {
            res.push_back(pre->val);
            pre = pre->next;
        }
       return res;
    }
};
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 文章大綱:1.題目簡介2.重點分析3.知識拓展 1.題目簡介 輸入一個鏈表的頭結點,從尾到頭反過來打印出每個節點的...
    檸檬烏冬面閱讀 512評論 2 2
  • 說明: 本文中出現的所有算法題皆來自??途W-劍指Offer在線編程題,在此只是作為轉載和記錄,用于本人學習使用,不...
    秋意思寒閱讀 1,170評論 1 1
  • 劍指 offer 在一個二維數組中,每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成...
    faremax閱讀 2,246評論 0 7
  • 1.把二元查找樹轉變成排序的雙向鏈表 題目: 輸入一棵二元查找樹,將該二元查找樹轉換成一個排序的雙向鏈表。 要求不...
    曲終人散Li閱讀 3,371評論 0 19
  • 題目 不想打了,如題吧 1:逆置鏈表然后打印,這個做法的缺點是要改變輸入的值,題目沒有明確這個要求的話,做起來有風...
    clshinem閱讀 137評論 0 1