Skip to content

Commit c0759a0

Browse files
author
Antesh Sharma
committed
reverse a linkedList in TC o(n) and SC: O(1)
1 parent cb11dbd commit c0759a0

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
package com.antesh.dsa;
2+
3+
/* Given a linked list, output it's reverse
4+
5+
- Initialize three pointers prev as NULL, curr as head and next as NULL.
6+
- Iterate through the linked list. In loop, do following.
7+
// Before changing next of current,
8+
// store next node
9+
next = curr->next
10+
// Now change next of current
11+
// This is where actual reversing happens
12+
curr->next = prev
13+
// Move prev and curr one step forward
14+
prev = curr
15+
curr = next
16+
17+
Time Complexity: O(n)
18+
Space Complexity: O(1)
19+
20+
*/
21+
public class ReverseALinkedList {
22+
23+
static Node root;
24+
25+
static class Node {
26+
int data;
27+
Node next;
28+
29+
public Node(int data) {
30+
this.data = data;
31+
this.next = null;
32+
}
33+
}
34+
35+
public static Node insert(Node root, int data) {
36+
if (root == null) {
37+
return new Node(data);
38+
}
39+
40+
Node temp = new Node(data);
41+
Node ptr = root;
42+
while (ptr.next != null) {
43+
ptr = ptr.next;
44+
}
45+
ptr.next = temp;
46+
47+
return root;
48+
}
49+
50+
public static Node reverse(Node head) {
51+
if (head == null) {
52+
return head;
53+
}
54+
55+
Node prev = null;
56+
Node curr = head;
57+
Node temp = null;
58+
59+
while (curr != null) {
60+
temp = curr.next;
61+
curr.next = prev;
62+
prev = curr;
63+
curr = temp;
64+
}
65+
66+
head = prev;
67+
return head;
68+
}
69+
70+
public static void print(Node root) {
71+
while (root != null) {
72+
System.out.print(root.data + " ");
73+
root = root.next;
74+
}
75+
}
76+
77+
public static void main(String[] args) {
78+
int[] arr = {10, 20, 30, 40, 50};
79+
for (int i = 0; i < arr.length; i++) {
80+
root = insert(root, arr[i]);
81+
}
82+
83+
System.out.println("Print input list: ");
84+
print(root);
85+
86+
System.out.println();
87+
root = reverse(root);
88+
System.out.println("Print reversed list: ");
89+
print(root);
90+
91+
92+
}
93+
}

0 commit comments

Comments
 (0)