當(dāng)前位置:首頁 > IT技術(shù) > 其他 > 正文

劍指 Offer 06. 從尾到頭打印鏈表
2022-05-29 22:28:21

劍指 Offer 06. 從尾到頭打印鏈表

輸入一個鏈表的頭節(jié)點,從尾到頭反過來返回每個節(jié)點的值(用數(shù)組返回)。

?

示例 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/

開通會員,享受整站包年服務(wù)立即開通 >