剑指 Offer 06. 从尾到头打印链表

90 阅读1分钟

没太大难度,主要适应C++的STL使用

vector 容器

void push_back(const T& x):向量尾部增加一个元素X

void clear():清空向量中所有元素

void pop_back():删除向量中最后一个元素

int size() const:返回向量中元素的个数

Stack 容器 empty() 堆栈为空则返回真

pop() 移除栈顶元素

push() 在栈顶增加元素

size() 返回栈中元素数目

top() 返回栈顶元素

/**
 * 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) {
        ListNode* node = head;
        stack<int> s;
        vector<int> arr;
        // 入栈
        while(node != NULL){
            s.push(node->val);
            node = node->next;
        }
        // 出栈放入数组
        while(!s.empty()){
            arr.push_back(s.top());
            s.pop();
        }
        return arr;
    }
};