Neo's Blog

不抽象就无法深入思考
不还原就看不到本来面目!

0%

链表系列-链表逆序打印到数组

输入一个链表的头结点,按照 从尾到头 的顺序返回节点的值。

返回的结果用数组存储。

样例
输入:[2, 3, 5]
返回:[5, 3, 2]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> printListReversingly(ListNode* head) {
vector<int> r;
while (head) {
r.push_back(head->val);
head = head->next;
}
return vector<int>(r.rbegin(), r.rend());
}
};

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> res;

void reverse(ListNode* head) {
if (!head) return;
reverse(head->next);
res.push_back(head->val);
}

vector<int> reversePrint(ListNode* head) {
reverse(head);
return res;
}
};
你的支持是我坚持的最大动力!