06_从尾到头打印链表

从尾到头打印链表

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例 1:

输入:head = [1,3,2]
输出:[2,3,1]
 

限制:

0 <= 链表长度 <= 10000

解法: 遍历链表,将链表中的值放到一个栈(先进后出)中,再将栈中中的值出栈放到一个数组中。

遇到的问题: pop()不会返回栈顶元素。为了安全性和效率-> 如果pop()返回栈顶元素,则必须按值返回,而不是按引用返回。按值返回效率低下,会在返回的过程中调用构造函数。
所以STL采用了先用top()后用pop()

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        stack<int> list;
        vector<int> result;
        ListNode* pNode = head;
        while (pNode!= nullptr){
            list.push(pNode->val);
            pNode = pNode->next;
        }
        while(!list.empty()){
            int temp = list.top();
            result.push_back(temp);
            list.pop();
        }
        return result;
    }
};
发布了46 篇原创文章 · 获赞 19 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/li123_123_/article/details/104325409
今日推荐