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

本题来自《剑指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:

总结:

猜你喜欢

转载自www.cnblogs.com/missidiot/p/10751135.html
今日推荐