forked from morethink/algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTest5.java
More file actions
74 lines (64 loc) · 1.85 KB
/
Test5.java
File metadata and controls
74 lines (64 loc) · 1.85 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package algorithm.swordtooffer;
/**
* @author 李文浩
* @version 2017/7/29.
* <p>
* 输入一个链表,从尾到头打印链表每个节点的值。
*/
import java.util.ArrayList;
public class Test5 {
public static class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public static void main(String[] args) {
ListNode listNode = new ListNode(1);
ListNode listNode2 = new ListNode(2);
ListNode listNode3 = new ListNode(3);
listNode.next = listNode2;
listNode2.next = listNode3;
System.out.println(new Test5().printListFromTailToHead(listNode));
}
/**
* 解决问题有两种方法
* 1. 翻转链表
* 2. 将链表的值存储之后在翻转
*
* 查看别人发现,还可使用递归,其实你应该明白凡是跟栈相关的都可通过递归实现
* @param listNode
* @return
*/
// public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
// Stack<Integer> stack = new Stack<>();
// while (listNode != null) {
// stack.push(listNode.val);
// listNode = listNode.next;
//
// }
// ArrayList arrayList = new ArrayList();
// while (!stack.isEmpty()) {
// arrayList.add(stack.pop());
// }
// System.out.println(arrayList);
// return arrayList;
// }
/**
* 递归版本
*
* @param listNode
* @return
*/
private ArrayList<Integer> arrayList = new ArrayList<>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if (listNode == null) {
return arrayList;
} else {
printListFromTailToHead(listNode.next);
arrayList.add(listNode.val);
}
return arrayList;
}
}