-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathReverseLinkedList.java
More file actions
84 lines (72 loc) · 1.86 KB
/
Copy pathReverseLinkedList.java
File metadata and controls
84 lines (72 loc) · 1.86 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
/*
This is an implementation that shows how
to reverse a singly linked list in place.
Each linked list node has an integer value
as well as a next pointer that points to
the next node or null in case of tail of list.
Let n be the number of nodes in the list.
Time complexity: O(n)
Space complexity: O(1)
*/
public class ReverseLinkedList {
private ListNode head;
public ReverseLinkedList() {
/*
* Create below linked list
* 0 -> 1 -> 2 -> 3 -> 4 -> 5
*/
head = new ListNode(0, null);
ListNode prev = head, temp;
for (int i = 1; i <= 5; i++) {
temp = new ListNode(i, null);
prev.next = temp;
prev = temp;
}
}
// Print elements of linked list starting from head
private void printLinkedList() {
ListNode temp = head;
while (temp != null) {
System.out.print(temp.val + " ");
temp = temp.next;
}
System.out.println();
}
public static void main(String[] args) {
ReverseLinkedList application = new ReverseLinkedList();
application.printLinkedList(); // 0 1 2 3 4 5
application.reverseList();
application.printLinkedList(); // 5 4 3 2 1 0
}
public void reverseList() {
if (head == null || head.next == null) {
return;
}
// Three pointers are used to allow for
// efficient reversal of the list
ListNode previousNode = null;
ListNode currentNode = head;
ListNode nextNode;
while (currentNode != null) {
// Keep updating next, current, and
// previous pointers properly until
// end of list is reached.
nextNode = currentNode.next;
currentNode.next = previousNode;
previousNode = currentNode;
currentNode = nextNode;
}
// List has a new head
head = previousNode;
}
// Class representing a linked list node
// with pointers to value and next node
private class ListNode {
int val;
ListNode next;
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
}