-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReserveList.java
More file actions
96 lines (82 loc) · 2.07 KB
/
ReserveList.java
File metadata and controls
96 lines (82 loc) · 2.07 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package linkedlist;
import linkedlist.common.DNode;
import linkedlist.common.Node;
import linkedlist.common.TNode;
import org.junit.Test;
/**
* Created by LXF on 2016/7/27.
*/
public class ReserveList {
/*不带头结点的反转*/
public Node reverse(Node head) {
Node pre,next;
pre = next = null;
while (head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
/*带头结点的头插法反转*/
public TNode reserve1(TNode head) {
TNode cur = head.next;
head.next = null;
TNode next;
while (cur != null) {
next = cur.next;
cur.next = head.next;
head.next = cur;
cur = next;
}
return head;
}
/*反转双链表*/
public DNode reserveD(DNode head) {
DNode pre,next;
pre = next = null;
while (head != null) {
next = head.next;
head.next = pre;
head.last = next;
pre = head;
head = next;
}
return pre;
}
@Test
public void test() {
Node head = new Node(2);
head.add(3);
ReserveList reserveList = new ReserveList();
Node res = reserveList.reverse(head);
System.out.println(res.next.value);
}
@Test
public void testT() {
TNode head = new TNode();
head.add(3);
head.add(4);
head.add(5);
ReserveList reserveList = new ReserveList();
TNode res = reserveList.reserve1(head);
while (res != null) {
System.out.println(res.value);
res = res.next;
}
}
@Test
public void testD() {
DNode head = new DNode(3);
head.add(4);
head.add(42);
head.add(56);
ReserveList reserveList = new ReserveList();
DNode res = reserveList.reserveD(head);
while (res != null) {
System.out.println(res.value);
res = res.next;
}
}
}