-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathreverseSLL.java
75 lines (64 loc) · 1.88 KB
/
reverseSLL.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
import java.util.ArrayList;
/**
* Given a SLL, reverse it
* ip: 10->20->30->40
* op: 40->30->20->10
*
* Naive: use an aux array, copy contents of LL into the array
* then we traverse the linked list again, we copy of aux array into LL in reverese order
* Time: O(2n) Space: O(n)
*
* Eff: Change the links
* we store curr's next in a var nextNode
* then we point curr's next to prevNode
* then we set prev and curr for next itr by moving curr and next
* i.e prev = curr and curr=next
*
* Throughout the process, nextNode is maintained only for keeping track of items ahead of curr node
*
* it would be better if you imagine 3 nodes having names prev, curr and next
*
* Time: O(n), Space: O(1)
*/
public class reverseSLL {
public static void main(String[] args) {
Node head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
// head = naive_itr(head);
head = eff_itr(head);
printList(head);
}
public static Node naive_itr(Node head) {
ArrayList<Integer> arr = new ArrayList<Integer>();
for (Node curr = head; curr != null; curr = curr.next)
arr.add(curr.data);
for (Node curr = head; curr != null; curr = curr.next)
curr.data = arr.remove(arr.size() - 1);
return head;
}
public static Node eff_itr(Node head) {
Node curr = head;
Node prev = null;
while(curr!=null)
{
Node nextNode = curr.next;
curr.next = prev;
prev = curr;
curr = nextNode;
}
return prev;
}
public static void printList(Node head) {
Node traverse = head;
while (traverse != null) {
System.out.print(traverse.data + "->");
traverse = traverse.next;
}
System.out.print("null\n");
}
}
/**
* op
* 30->20->10->null
*/