-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution006.java
More file actions
66 lines (53 loc) · 1.55 KB
/
Solution006.java
File metadata and controls
66 lines (53 loc) · 1.55 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
package com.portgas;
import java.util.ArrayList;
public class Solution006 {
public static class ListNode {
public Integer value;
public ListNode next;
public ListNode(int i) {
value = i;
}
}
/**
* 输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
**/
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if (listNode == null) {
return null;
}
ArrayList<Integer> arrayList = new ArrayList<>();
ListNode revertList = revertList1(listNode);
while (revertList != null) {
arrayList.add(revertList.value);
revertList = revertList.next;
}
return arrayList;
}
// 头插法
private ListNode revertList1(ListNode listNode) {
ListNode head = new ListNode(-1);
while (listNode != null) {
ListNode temp = listNode.next;
listNode.next = head.next;
head.next = listNode;
listNode = temp;
}
return head.next;
}
// 递归法
private ListNode revertList2(ListNode listNode) {
if (listNode == null) {
return null;
}
if (listNode.next == null) {
return listNode;
}
ListNode next = listNode.next;
ListNode revertList = revertList2(listNode.next);
if (revertList != null) {
next.next = listNode;
listNode.next = null; // 防止回环
}
return revertList;
}
}