File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed
Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments