|
| 1 | +package LinkedList; |
| 2 | + |
| 3 | +public class ReverseSize { |
| 4 | + Node head; // head of list |
| 5 | + |
| 6 | + /* Linked list Node*/ |
| 7 | + class Node { |
| 8 | + int data; |
| 9 | + Node next; |
| 10 | + Node(int d) |
| 11 | + { |
| 12 | + data = d; |
| 13 | + next = null; |
| 14 | + } |
| 15 | + } |
| 16 | + |
| 17 | + Node reverse(Node head, int k) |
| 18 | + { |
| 19 | + if(head == null) |
| 20 | + return null; |
| 21 | + Node current = head; |
| 22 | + Node next = null; |
| 23 | + Node prev = null; |
| 24 | + |
| 25 | + int count = 0; |
| 26 | + |
| 27 | + /* Reverse first k nodes of linked list */ |
| 28 | + while (count < k && current != null) { |
| 29 | + next = current.next; |
| 30 | + current.next = prev; |
| 31 | + prev = current; |
| 32 | + current = next; |
| 33 | + count++; |
| 34 | + } |
| 35 | + |
| 36 | + /* next is now a pointer to (k+1)th node |
| 37 | + Recursively call for the list starting from |
| 38 | + current. And make rest of the list as next of |
| 39 | + first node */ |
| 40 | + if (next != null) |
| 41 | + head.next = reverse(next, k); |
| 42 | + |
| 43 | + // prev is now head of input list |
| 44 | + return prev; |
| 45 | + } |
| 46 | + |
| 47 | + /* Utility functions */ |
| 48 | + |
| 49 | + /* Inserts a new Node at front of the list. */ |
| 50 | + public void push(int new_data) |
| 51 | + { |
| 52 | + /* 1 & 2: Allocate the Node & |
| 53 | + Put in the data*/ |
| 54 | + Node new_node = new Node(new_data); |
| 55 | + |
| 56 | + /* 3. Make next of new Node as head */ |
| 57 | + new_node.next = head; |
| 58 | + |
| 59 | + /* 4. Move the head to point to new Node */ |
| 60 | + head = new_node; |
| 61 | + } |
| 62 | + |
| 63 | + /* Function to print linked list */ |
| 64 | + void printList() |
| 65 | + { |
| 66 | + Node temp = head; |
| 67 | + while (temp != null) { |
| 68 | + System.out.print(temp.data + " "); |
| 69 | + temp = temp.next; |
| 70 | + } |
| 71 | + System.out.println(); |
| 72 | + } |
| 73 | + |
| 74 | + /* Driver program to test above functions */ |
| 75 | + public static void main(String args[]) |
| 76 | + { |
| 77 | + ReverseSize llist = new ReverseSize(); |
| 78 | + |
| 79 | + /* Constructed Linked List is 1->2->3->4->5->6-> |
| 80 | + 7->8->8->9->null */ |
| 81 | + llist.push(9); |
| 82 | + llist.push(8); |
| 83 | + llist.push(7); |
| 84 | + llist.push(6); |
| 85 | + llist.push(5); |
| 86 | + llist.push(4); |
| 87 | + llist.push(3); |
| 88 | + llist.push(2); |
| 89 | + llist.push(1); |
| 90 | + |
| 91 | + System.out.println("Given Linked List"); |
| 92 | + llist.printList(); |
| 93 | + |
| 94 | + llist.head = llist.reverse(llist.head, 3); |
| 95 | + |
| 96 | + System.out.println("Reversed list"); |
| 97 | + llist.printList(); |
| 98 | + } |
| 99 | +} |
0 commit comments