In this program, we are going to share a Java program to reverse a linked list in groups of given size. If you are a Java beginner and want to start learning the Java programming, then keep your close attention in this tutorial as I am going to share how to write a Java program to reverse a linked list in groups of given size.
To increase your Java knowledge, practice all Java programs:
Copy the below Java program and execute it with the help of Javac compiler. At the end of this program, We have shared the output of this program.
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 76 | class LinkedList { Node head; class Node { int data; Node next; Node(int d) {data = d; next = null; } } Node reverse(Node head, int k) { Node current = head; Node next = null; Node prev = null; int count = 0; while (count < k && current != null) { next = current.next; current.next = prev; prev = current; current = next; count++; } if (next != null) head.next = reverse(next, k); return prev; } public void push(int new_data) { Node new_node = new Node(new_data); new_node.next = head; head = new_node; } void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data+" "); temp = temp.next; } System.out.println(); } public static void main(String args[]) { LinkedList llist = new LinkedList(); llist.push(9); llist.push(8); llist.push(7); llist.push(6); llist.push(5); llist.push(4); llist.push(3); llist.push(2); llist.push(1); System.out.println("Given Linked List"); llist.printList(); llist.head = llist.reverse(llist.head, 3); System.out.println("Reversed list"); llist.printList(); } } |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.