剑指offer面试题【6】--从头到尾打印链表【栈】【单链表】【C++】

题目描述 

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

代码实现

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> result;
        stack<int> arr;
        ListNode* p=head;
        while(p!=NULL){
            arr.push(p->val);//push()进栈函数
            p=p->next;
        }
        int len=arr.size();
        for (int i=0;i<len;i++){
            result.push_back(arr.top());//top()取栈顶元素;
            //vector头文件里面就有push_back函数,作用为在vector尾部加入一个数据。
            arr.pop();//pop()弹出栈顶元素
        }
        return result;
            
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_42702666/article/details/88593698