首页 > 其他 > 详细

剑指offer 《从尾到头打印链表》

时间:2019-04-22 17:12:17      阅读:119      评论:0      收藏:0      [点我收藏+]

本题来自《剑指offer》 从尾到头打印链表

题目:

  输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

思路:

C++ Code (栈方式):

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        std::vector<int> result;           //存放结果值
        std::stack<ListNode*> nodes;       //栈,存放其节点的值
        ListNode* phead = head;
        int val;
        while (phead != NULL){             //遍历链表
            nodes.push(phead);             //将节点加入到栈中
            phead = phead->next;
        }
        while (!nodes.empty()){            //从栈中取数据
            val = nodes.top()->val;
            result.push_back(val);
            nodes.pop();
        }
        return result;
    }
};

C++ Code (递归方式):

Python Code:

总结:

剑指offer 《从尾到头打印链表》

原文:https://www.cnblogs.com/missidiot/p/10751135.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!