ACwing刷题笔记 17. 从尾到头打印链表
思路
输出的顺序是从后往前,那么可以使用栈这种数据结构,每次经过一个节点,就将该节点放入栈中。当遍历完整个链表之后,在从栈顶开始依次输出各个节点的值。
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> printListReversingly(ListNode* head) {
vector<int> result;//存放结果
stack<int> st;
ListNode *p = head;
while(p != NULL)
{
st.push(p->val);
p = p->next;
}
// 出栈 打印数值
while(!st.empty())
{
result.push_back(st.top());
st.pop();
}
return result;
}
};