forked from anitaa1990/Android-Cheat-sheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReverseLinkedList.java
68 lines (53 loc) · 1.69 KB
/
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
package linkedlist;
public class ReverseLinkedList {
/*
* Runtime Complexity:
* Linear, O(n).
* As we can reverse the linked list in a single pass.
*
* Memory Complexity:
* Constant, O(1).
* As no extra memory is required for the iterative solution.
* */
private static class LinkedList {
private LinkedList.Node head;
public Node reverse(Node node) {
Node previous = null;
Node current = node;
Node next = null;
while (current != null) {
next = current.next;
current.next = previous;
previous = current;
current = next;
}
node = previous;
return node;
}
public void printList(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
public static class Node {
private int data;
private Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
}
public static void main(String [] args) {
LinkedList linkedList = new LinkedList();
linkedList.head = new LinkedList.Node(1);
linkedList.head.next = new LinkedList.Node(2);
linkedList.head.next.next = new LinkedList.Node(3);
linkedList.head.next.next.next = new LinkedList.Node(4);
linkedList.printList(linkedList.head);
linkedList.head = linkedList.reverse(linkedList.head);
System.out.println("");
linkedList.printList(linkedList.head);
}
}