forked from kubrafelek/LeetCodes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_0206_ReverseLinkedList.java
80 lines (61 loc) · 1.4 KB
/
_0206_ReverseLinkedList.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
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
public class _0206_ReverseLinkedList {
ListNode first;
ListNode last;
public static void main(String[] args) {
_0206_ReverseLinkedList t1 = new _0206_ReverseLinkedList();
ListNode l1 = new ListNode(1);
ListNode l2 = new ListNode(2);
ListNode l3 = new ListNode(3);
ListNode l4 = new ListNode(4);
t1.insertFirst(l1);
t1.insertFirst(l2);
t1.insertFirst(l3);
t1.insertFirst(l4);
System.out.println(t1.toString());
t1.reverseList(l4);
t1.insertFirst(l3);
t1.insertFirst(l2);
t1.insertFirst(l1);
System.out.println(t1.toString());
}
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode current = head;
while (current != null) {
ListNode nextTemp = current.next;
current.next = prev;
prev = current;
current = nextTemp;
}
return prev;
}
public void insertFirst(ListNode newNode) {
if (first == null) {
first = newNode;
last = newNode;
} else {
newNode.next = first;
first = newNode;
}
}
public String toString() {
ListNode tmp = first;
String str = "";
while (tmp != null) {
str += tmp.val + " -> ";
tmp = tmp.next;
}
return str + "NULL";
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
@Override
public String toString() {
return "\nListNode [val=" + val + ", next=" + next + "]";
}
}