题目
输入一个链表的头结点,按照 从尾到头 的顺序返回节点的值。
返回的结果用数组存储。
数据范围 0≤0≤ 链表长度 ≤1000≤1000。
样例 输入:[2, 3, 5] 返回:[5, 3, 2]
解析
链表遍历到数组中,然后反转数组就行
代码
C++
/**
* 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> ans;
while (head) {
ans.push_back(head->val);
head = head->next;
}
return vector<int>(ans.rbegin(), ans.rend());
}
};
Python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def printListReversingly(self, head):
"""
:type head: ListNode
:rtype: List[int]
"""
ans = []
while head:
ans.append(head.val)
head = head.next
return ans[::-1]
GO
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func printListReversingly(head *ListNode) []int {
var ans []int
for head != nil {
ans = append(ans, head.Val)
head = head.Next
}
return reverse(ans)
}
func reverse(list []int) ([]int) {
var reList []int
for i := len(list) - 1; i >= 0; i -- {
reList = append(reList, list[i])
}
return reList
}