剑指 Offer 06. 从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2] 输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 vector<int> reversePrint(ListNode* head) { 12 vector<int> ans; 13 stack<int> stk; 14 while (head != nullptr) { 15 stk.push(head->val); 16 head = head->next; 17 } 18 while (!stk.empty()) { 19 int top = stk.top(); 20 stk.pop(); 21 ans.emplace_back(top); 22 } 23 return ans; 24 } 25 };
本文摘自 :https://www.cnblogs.com/