美文网首页
剑指Offer -- 从尾到头打印链表(C++)

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

作者: 白夜叉小分队 | 来源:发表于2018-04-26 01:14 被阅读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;
    }
};

相关文章

网友评论

      本文标题:剑指Offer -- 从尾到头打印链表(C++)

      本文链接:https://www.haomeiwen.com/subject/shgulftx.html