|
| 1 | +package me.ramswaroop.linkedlists; |
| 2 | + |
| 3 | +import me.ramswaroop.common.SingleLinkedList; |
| 4 | +import me.ramswaroop.common.SingleLinkedNode; |
| 5 | + |
| 6 | +/** |
| 7 | + * Created by IntelliJ IDEA. |
| 8 | + * |
| 9 | + * @author: ramswaroop |
| 10 | + * @date: 7/3/15 |
| 11 | + * @time: 3:07 PM |
| 12 | + */ |
| 13 | +public class RotateLinkedList { |
| 14 | + |
| 15 | + /** |
| 16 | + * Rotates the {@param list} anti-clockwise by {@param k} nodes. |
| 17 | + * |
| 18 | + * @param list |
| 19 | + * @param k |
| 20 | + * @param <E> |
| 21 | + */ |
| 22 | + public static <E extends Comparable<E>> void rotateCounterClockwise(SingleLinkedList<E> list, int k) { |
| 23 | + int clockwiseK = list.size - k; |
| 24 | + rotateClockwise(list, clockwiseK); |
| 25 | + } |
| 26 | + |
| 27 | + |
| 28 | + /** |
| 29 | + * Rotates the {@param list} clockwise by {@param k} nodes. |
| 30 | + * |
| 31 | + * Example, |
| 32 | + * |
| 33 | + * Input: [0,11,22,33,44,55] and k =2 |
| 34 | + * Output: [22,33,44,55,0,11] |
| 35 | + * |
| 36 | + * @param list |
| 37 | + * @param k |
| 38 | + * @param <E> |
| 39 | + */ |
| 40 | + public static <E extends Comparable<E>> void rotateClockwise(SingleLinkedList<E> list, int k) { |
| 41 | + int i = 0; |
| 42 | + SingleLinkedNode<E> curr = list.head, end = curr; |
| 43 | + |
| 44 | + // get a pointer to the last node |
| 45 | + while (end.next != null) { |
| 46 | + end = end.next; |
| 47 | + } |
| 48 | + |
| 49 | + // start moving first k nodes from start to end |
| 50 | + while (i < k && k < list.size) { |
| 51 | + end.next = curr; |
| 52 | + end = end.next; |
| 53 | + curr = curr.next; |
| 54 | + i++; |
| 55 | + } |
| 56 | + |
| 57 | + // change head to k+1 node |
| 58 | + list.head = curr; |
| 59 | + end.next = null; |
| 60 | + |
| 61 | + } |
| 62 | + |
| 63 | + public static void main(String a[]) { |
| 64 | + SingleLinkedList<Integer> linkedList = new SingleLinkedList<>(); |
| 65 | + linkedList.add(00); |
| 66 | + linkedList.add(11); |
| 67 | + linkedList.add(22); |
| 68 | + linkedList.add(33); |
| 69 | + linkedList.add(44); |
| 70 | + linkedList.add(55); |
| 71 | + linkedList.printList(); |
| 72 | + rotateClockwise(linkedList, 2); |
| 73 | + linkedList.printList(); |
| 74 | + rotateCounterClockwise(linkedList, 2); |
| 75 | + linkedList.printList(); |
| 76 | + } |
| 77 | +} |
0 commit comments