剑指Offer -- 从尾到头打印链表(C++)

2018-04-26  本文已影响12人  白夜叉小分队
题目描述

输入一个链表,从尾到头打印链表每个节点的值。

方法1:注意是从尾到头进行打印,可利用vector的头插法。

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> allData;
        while (head != NULL) {
            allData.insert(allData.begin(), head->val);
            head = head->next;
        }
        return allData;
    }
};

方法2:直接将vector进行反向。

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> allData;
        while (head != NULL) {
            allData.push_back(head->val);
            head = head->next;
        }
        reverse(allData.begin(), allData.end());
        return allData;
    }
};

方法3:利用栈先进后出的特性。

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> allData;
        stack<int> value;
        while (head != NULL) {
            value.push(head->val);
            head = head->next;
        }
        while (!value.empty()) {
            allData.push_back(value.top());
            value.pop();//C++,不返回元素 
        }
        return allData;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读