Skip to content

Commit 47708ee

Browse files
authored
Merge pull request #452 from prtk418/prtk418_reverse_linked_list_in_java
reverse link list in java
2 parents 1d918f6 + 8e7eab7 commit 47708ee

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

linked_list/reverse_link_list.java

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// Java program for reversing the linked list
2+
3+
class LinkedList {
4+
5+
static Node head;
6+
7+
static class Node {
8+
9+
int data;
10+
Node next;
11+
12+
Node(int d) {
13+
data = d;
14+
next = null;
15+
}
16+
}
17+
18+
/* Function to reverse the linked list */
19+
Node reverse(Node node) {
20+
Node prev = null;
21+
Node current = node;
22+
Node next = null;
23+
while (current != null) {
24+
next = current.next;
25+
current.next = prev;
26+
prev = current;
27+
current = next;
28+
}
29+
node = prev;
30+
return node;
31+
}
32+
33+
// prints content of double linked list
34+
void printList(Node node) {
35+
while (node != null) {
36+
System.out.print(node.data + " ");
37+
node = node.next;
38+
}
39+
}
40+
41+
public static void main(String[] args) {
42+
LinkedList list = new LinkedList();
43+
list.head = new Node(45);
44+
list.head.next = new Node(55);
45+
list.head.next.next = new Node(78);
46+
list.head.next.next.next = new Node(20);
47+
48+
System.out.println("Given Linked list");
49+
list.printList(head);
50+
head = list.reverse(head);
51+
System.out.println("");
52+
System.out.println("Reversed linked list ");
53+
list.printList(head);
54+
}
55+
}

0 commit comments

Comments
 (0)