JZ03 从尾到头打印链表

本文最后更新于:2022年4月9日 中午

image-20211006100701326

Solution

  • 迭代法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> array;
ListNode* cur = head;
while (cur) {
// 头插法
array.insert(array.begin(), cur->val);
cur = cur->next;
}
return array;
}
};
  • 递归法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
res.clear();
travel(head);
return res;
}
private:
vector<int> res;
void travel(ListNode* head) {
if (head == nullptr) return;
travel(head->next);
res.push_back(head->val);
}
};

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!