从尾到头打印链表
输入一个链表,从尾到头打印链表每个节点的值。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
//输入一个链表,从尾到头打印链表每个节点的值。
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
stack<int> stack;
vector<int> vector;
struct ListNode *pNode = head;
if (head != NULL) {
stack.push(pNode->val);
while((pNode=pNode->next) != NULL) {
stack.push(pNode->val);
}
while(!stack.empty()) {
//vector的末尾插入一个元素
vector.push_back(stack.top());
stack.pop();
}
}
return vector;
}
};