LinkList

题目描述[原题链接][https://www.acwing.com/problem/content/description/18/]

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

返回的结果用数组存储。

样例

1
2
输入:[2, 3, 5]
返回:[5, 3, 2]

算法描述

遍历一遍链表,每次访问一个节点将节点的值添加到数组中,遍历完成后,反转数组输出结果即可;

java做法遍历链表,将每个节点的值存放到List中,完成后,初始化数组,将链表中的值取出逆序存放到数组中,输出结果即可;

C++代码

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
vector<int> printListReversingly(ListNode* head) {
vector<int> vec;
if(head == NULL)return vec;
ListNode* p = head;
while(p!=NULL){
vec.push_back(p->val);
p = p->next;
}
return vector<int>(vec.rbegin(),vec.rend());
}
};

Java代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int[] printListReversingly(ListNode head) {
List<Integer> list = new ArrayList<>();

while(head!=null){
list.add(head.val);
head = head.next;
}

int[] ans =new int[list.size()];
int t=list.size()-1;
for(int i=0;i<list.size();i++){
ans[t--]=list.get(i);
}
return ans;
}
}