|
| 1 | +package com.antesh.dsa.linkedlist; |
| 2 | + |
| 3 | + |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +/** |
| 7 | + * Problem Reference: https://github.com/aniketskulkarni/coding-problems/blob/master/LeetCode/src/com/java7/problem/easy/linkedlist/OddEvenLinkedList.java |
| 8 | + * |
| 9 | + * Given the head of a singly linked list, group all the nodes with odd indices |
| 10 | + * together followed by the nodes with even indices, and return the reordered |
| 11 | + * list. |
| 12 | + * |
| 13 | + * The first node is considered odd, and the second node is even, and so on. |
| 14 | + * Note that the relative order inside both the even and odd groups should |
| 15 | + * remain as it was in the input. |
| 16 | + * You must solve the problem in O(1) extra space complexity and O(n) time |
| 17 | + * complexity. |
| 18 | + * |
| 19 | + * Input: head = [1,2,3,4,5] |
| 20 | + * Output: [1,3,5,2,4] |
| 21 | + */ |
| 22 | + |
| 23 | +public class OddEvenLinkedList { |
| 24 | + ListNode head; |
| 25 | + |
| 26 | + class ListNode { |
| 27 | + int data; |
| 28 | + ListNode next; |
| 29 | + |
| 30 | + public ListNode(int data) { |
| 31 | + this.data = data; |
| 32 | + this.next = null; |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + public void addAtTail(int data) { |
| 37 | + if (head == null) { |
| 38 | + head = new ListNode(data); |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + ListNode currentNode = head; |
| 43 | + while (currentNode.next != null) { |
| 44 | + currentNode = currentNode.next; |
| 45 | + } |
| 46 | + ListNode newNode = new ListNode(data); |
| 47 | + currentNode.next = newNode; |
| 48 | + } |
| 49 | + |
| 50 | + public static ListNode oddEvenLinkedList(ListNode head) { |
| 51 | + if (head == null) { |
| 52 | + return head; |
| 53 | + } |
| 54 | + |
| 55 | + ListNode currentNode = head; //1 -> 2 -> 3 -> 4 -> 5 |
| 56 | + |
| 57 | + while (currentNode.next != null && currentNode.next.next != null) { |
| 58 | + ListNode nextNode = currentNode.next; // 2 -> 3 |
| 59 | + ListNode nextToNextNode = currentNode.next.next; // 3 -> 4 |
| 60 | + currentNode.next = currentNode.next.next; //1 -> 3 -> 4 |
| 61 | + //TODO: |
| 62 | + |
| 63 | + |
| 64 | + |
| 65 | + } |
| 66 | + |
| 67 | + |
| 68 | + } |
| 69 | + |
| 70 | +} |
0 commit comments