从尾到头打印链表
一、题目描述
输入一个链表,从尾到头打印链表每个节点的值。
二、我的思路
如果题目要求不改变链表结构,可以使用栈。
三、我的代码
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> vec;
stack<int> st;
ListNode *p = head;
while(p != NULL){
st.push(p->val);
p = p->next;
}
while(!st.empty()){
vec.push_back(st.top());
st.pop();
}
return vec;
}
};