GeeksforGeeks » Linked List specific questions
Reverse a linked list every "given num" nodes
(2 posts)-
Input (num = 3)
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10Output
3 -> 2 -> 1 -> 6 -> 5 -> 4 -> 9 -> 8 -> 7 -> 10public static LinkedListNode reverseWhole(LinkedListNode head, int num) { if (head == null || head.next == null) return head; LinkedListNode[] headAndTail = reversePart(head, num); LinkedListNode newHead = headAndTail[0]; LinkedListNode tail = headAndTail[1]; LinkedListNode next = tail.next; while (next != null && tail != null) { LinkedListNode[] nodes = reversePart(next, num); tail.next = nodes[0]; tail = nodes[1]; if (tail != null) next = tail.next; } return newHead; } /** * Reverse the linked list every "num" nodes. * * **/ private static LinkedListNode[] reversePart(LinkedListNode head, int num) { if (head == null || head.next == null) return new LinkedListNode[]{head, null}; LinkedListNode next = head.next; LinkedListNode current = head; LinkedListNode tail = head; for (int i = 0; i < num - 1 && next != null; i++) { LinkedListNode temp = next.next; next.next = current; current = next; next = temp; } head.next = next; return new LinkedListNode[]{current, head}; }I have attached my iterative solution here. Is there a recursive solution for it?
Also, let me know your comments about this iterative solution. -
Following post seens related. The code given there is recursive.
Reply
You must log in to post.