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

题目

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

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

示例 1:

1
2
输入:head = [1,3,2]
输出:[2,3,1]

题解

python

还是很好写的。很多数据结构的变换都不需要考虑。

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
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None

class Solution:
def reversePrint(self, head):
res = []
root = head
while root:
res.insert(0,root.val)
root = root.next
return res

if __name__ == '__main__':
L = [1,2,3,4,5]
Head = ListNode(1)
R = Head
i = 1
while i < len(L):
R.next = ListNode(L[i])
i += 1
R = R.next
a = Solution()
print(a.reversePrint(Head))

Java

这里用到了Stack

image-20200728215332498

img

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
35
36
37
38
39
40
41
42
package Slash_offer.easy;

import java.util.Stack;

//Definition for singly-linked list.
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public class Slash_offer_06_从尾到头打印链表 {
public static void main(String[] args) {
Slash_offer_06_从尾到头打印链表 slash_offer_06_从尾到头打印链表 = new Slash_offer_06_从尾到头打印链表();
int [] L = new int[]{1,2,3,4,5};
ListNode Head = new ListNode(1);
ListNode R = Head;
int i = 1;
while (i<L.length){
R.next = new ListNode(L[i++]);
R = R.next;
}
for (int i1 : slash_offer_06_从尾到头打印链表.reversePrint(Head)) {
System.out.println(i1);
}
}
public int[] reversePrint(ListNode head) {
Stack<Integer> integers = new Stack<>();
ListNode R = head;
while (R!=null){
integers.push(R.val);
R = R.next;
}
int length = integers.size();
int[] ints = new int[length];
for (int i = 0; i < length ; i++) {
ints[i] = integers.pop();
}
return ints;
}
}