题目描述
输入一个链表,从尾到头打印链表每个节点的值。
解题思路:由于栈是后入先出的,因此将链表存入栈中。然后依次弹出栈即可
1 /** 2 * struct ListNode { 3 * int val; 4 * struct ListNode *next; 5 * ListNode(int x) : 6 * val(x), next(NULL) { 7 * } 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<int> printListFromTailToHead(ListNode* head) { 13 vector<int> result; 14 stack<int> stack; 15 ListNode *pNode = head; 16 while(pNode != NULL) 17 { 18 stack.push(pNode->val); 19 pNode = pNode->next; 20 } 21 while(!stack.empty()) 22 { 23 result.push_back(stack.top()); 24 stack.pop(); 25 } 26 return result; 27 } 28 };