-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeetCode0206.java
49 lines (44 loc) · 1.34 KB
/
LeetCode0206.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
/* Reverse Linked List
* Example:
* Input: 1->2->3->4->5->NULL
* Output: 5->4->3->2->1->NULL
* */
public class LeetCode0206 {
public static void main(String args[]){
int[] input = new int[]{1,2,3,4,5};
ListNode head = buildListNode(input);
ListNode res = reverseList(head);
while(res != null) {
System.out.println(res.val);
res = res.next;
}
}
public static ListNode reverseList(ListNode head) {
ListNode previous = null;
ListNode current = head;
while(current != null){
ListNode temp = current.next;
current.next = previous;
previous = current;
current = temp;
}
return previous;
}
private static ListNode buildListNode(int[] input) {
ListNode first = null, last = null, newNode;
if (input.length > 0) {
for (int i = 0; i < input.length; i++) {
newNode = new ListNode(input[i]);
newNode.next = null;
if (first == null) {
first = newNode;
last = newNode;
} else {
last.next = newNode;
last = newNode;
}
}
}
return first;
}
}