The code provided is an implementation of a Reverse_AlternateKNodes class in Java that reverses alternate k nodes in a linked list. The linked list is represented using a Node class with an integer data field and a next pointer. The Reverse_AlternateKNodes class has the following methods:
Note: The implementation assumes 0-based indexing for counting the nodes in the linked list, meaning the first node is index 0. If you want to use 1-based indexing, you need to adjust the implementation accordingly. Also, the implementation does not handle cases where k is larger than the size of the linked list or when there are less than k nodes remaining to reverse, so make sure to handle such cases if needed.
class Reverse_AlternateKNodes { public static void main(String[] args) { Reverse_AlternateKNodes list = new Reverse_AlternateKNodes(); for (int i = 20; i > 0; i--) { list.push(i); } System.out.print("Given Linked List : "); list.printList(head); head = list.kAltReverse(head, 6); System.out.println(""); System.out.print("Modified Linked List : "); list.printList(head); } static Node head; class Node { int data; Node next; Node(int d) { data = d; next = null; } } Node kAltReverse(Node node, int k) { Node current = node; Node next = null, prev = null; int count = 0; while (current != null && count < k) { next = current.next; current.next = prev; prev = current; current = next; count++; } if (node != null) { node.next = current; } count = 0; while (count < k - 1 && current != null) { current = current.next; count++; } if (current != null) { current.next = kAltReverse(current.next, k); } return prev; } void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } } void push(int newdata) { Node mynode = new Node(newdata); mynode.next = head; head = mynode; } }
Given Linked List : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Modified Linked List : 6 5 4 3 2 1 7 8 9 10 11 12 18 17 16 15 14 13 19 20
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions