-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_24_ReverseList.java
54 lines (45 loc) · 1.06 KB
/
_24_ReverseList.java
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
package swordtooffer;
/**
* 反转链表
*/
public class _24_ReverseList {
public Node reverseListRecursive(Node node) {
if (node == null) {
return null;
}
if (node.next == null) {
return node;
}
Node head = reverseListRecursive(node.next);
node.next.next = node;
node.next = null;
return head;
}
public Node reverseList(Node head) {
Node pReverse = null;
Node pNode = head;
Node pPre = null;
while (pNode != null) {
Node pNext = pNode.next;
if (pNext == null) {
pReverse = pNode;
}
pNode.next = pPre;
pPre = pNode;
pNode = pNext;
}
return pReverse;
}
public Node reverseList1(Node node) {
Node pre = null;
Node p = node;
Node pNext = null;
while (p != null) {
pNext = p.next;
p.next = pre;
pre = p;
p = pNext;
}
return pre;
}
}