|
| 1 | +package LinkedList; |
| 2 | + |
| 3 | +public class ReverseKNodes { |
| 4 | + static Node head; |
| 5 | + |
| 6 | + class Node { |
| 7 | + |
| 8 | + int data; |
| 9 | + Node next; |
| 10 | + |
| 11 | + Node(int d) { |
| 12 | + data = d; |
| 13 | + next = null; |
| 14 | + } |
| 15 | + } |
| 16 | + |
| 17 | + /* Reverses alternate k nodes and |
| 18 | + returns the pointer to the new head node */ |
| 19 | + Node kAltReverse(Node node, int k) { |
| 20 | + Node current = node; |
| 21 | + Node next = null, prev = null; |
| 22 | + int count = 0; |
| 23 | + |
| 24 | + /*1) reverse first k nodes of the linked list */ |
| 25 | + while (current != null && count < k) { |
| 26 | + next = current.next; |
| 27 | + current.next = prev; |
| 28 | + prev = current; |
| 29 | + current = next; |
| 30 | + count++; |
| 31 | + } |
| 32 | + |
| 33 | + /* 2) Now head points to the kth node. So change next |
| 34 | + of head to (k+1)th node*/ |
| 35 | + if (node != null) { |
| 36 | + node.next = current; |
| 37 | + } |
| 38 | + |
| 39 | + /* 3) We do not want to reverse next k nodes. So move the current |
| 40 | + pointer to skip next k nodes */ |
| 41 | + count = 0; |
| 42 | + while (count < k - 1 && current != null) { |
| 43 | + current = current.next; |
| 44 | + count++; |
| 45 | + } |
| 46 | + |
| 47 | + /* 4) Recursively call for the list starting from current->next. |
| 48 | + And make rest of the list as next of first node */ |
| 49 | + if (current != null) { |
| 50 | + current.next = kAltReverse(current.next, k); |
| 51 | + } |
| 52 | + |
| 53 | + /* 5) prev is new head of the input list */ |
| 54 | + return prev; |
| 55 | + } |
| 56 | + |
| 57 | + void printList(Node node) { |
| 58 | + while (node != null) { |
| 59 | + System.out.print(node.data + " "); |
| 60 | + node = node.next; |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + void push(int newdata) { |
| 65 | + Node mynode = new Node(newdata); |
| 66 | + mynode.next = head; |
| 67 | + head = mynode; |
| 68 | + } |
| 69 | + |
| 70 | + public static void main(String[] args) { |
| 71 | + ReverseKNodes list = new ReverseKNodes(); |
| 72 | + |
| 73 | + // Creating the linkedlist |
| 74 | + for (int i = 20; i > 0; i--) { |
| 75 | + list.push(i); |
| 76 | + } |
| 77 | + System.out.println("Given Linked List :"); |
| 78 | + list.printList(head); |
| 79 | + head = list.kAltReverse(head, 3); |
| 80 | + System.out.println(""); |
| 81 | + System.out.println("Modified Linked List :"); |
| 82 | + list.printList(head); |
| 83 | + |
| 84 | + } |
| 85 | +} |
0 commit comments