-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverse.java
More file actions
80 lines (69 loc) · 1.82 KB
/
Copy pathReverse.java
File metadata and controls
80 lines (69 loc) · 1.82 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
package linkedList;
import org.junit.Test;
public class Reverse {
/**
* @param head: n
* @return: The new head of reversed linked list.
* <p>
* <p>
* 35. 翻转链表
* 翻转一个链表
* <p>
* 样例
* 给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null
* <p>
* 挑战
* 在原地一次翻转完成
*/
public ListNode reverse(ListNode head) {
// write your code here
ListNode listNodePrev = null;
ListNode listNodeNext = null;
while (head != null) {
listNodeNext = head;
head = head.next;
listNodeNext.next = listNodePrev;
listNodePrev = listNodeNext;
}
return listNodeNext;
}
@Test
public void testReverse() {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
showList(head);
if (head == null) {
System.out.println("head == null");
}
showList(reverse(head));
}
public void showList(ListNode head) {
while (head != null) {
System.out.print(head.val+" ");
head = head.next;
}
}
public ListNode reverse2(ListNode head) {
if (head == null) {
return null;
}
ListNode former = null;
ListNode latter = null;
while (head != null) {
latter = head;
head = head.next;
latter.next = former;
former = latter;
}
return former;
}
@Test
public void test() {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
ListNode listNode = reverse2(head);
showList(listNode);
}
}