剑指 Offer 06. 从尾到头打印链表

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例 1:

1
2
输入:head = [1,3,2]
输出:[2,3,1]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:sarizzm time:2021/1/7 0007

# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None

class Solution:
def reversePrint(self, head):
pre = head
result = []
if head is None:
return result
while pre:
result.append(pre.val)
pre = pre.next
# result.reverse()
return result[::-1] # 速度比 result.reverse() 快且节省内存


n1 = [1,2,3,4,5,6]

def generate_node(n1):
head = ListNode(-1)
pre = head
for i in n1:
pre.next = ListNode(i)
pre = pre.next
return head.next

print(Solution().reversePrint(generate_node(n1)))

执行用时:44 ms, 在所有 Python3 提交中击败了77.69%的用户

内存消耗:16.1 MB, 在所有 Python3 提交中击败了33.87%的用户

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
Stack<ListNode> stack = new Stack<ListNode>();
ListNode temp = head;
while (temp != null) {
stack.push(temp);
temp = temp.next;
}
int size = stack.size();
int[] print = new int[size];
for (int i = 0; i < size; i++) {
print[i] = stack.pop().val;
}
return print;
}
}

//作者:LeetCode-Solution
//链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/solution/mian-shi-ti-06-cong-wei-dao-tou-da-yin-lian-biao-b/