Odd Even Linked List

Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.

You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.

Example 1:

Input: 1->2->3->4->5->NULL
Output: 1->3->5->2->4->NULL

Example 2:

Input: 2->1->3->5->6->4->7->NULL
Output: 2->3->6->7->1->5->4->NULL

Note:

  • The relative order inside both the even and odd groups should remain as it was in the input.
  • The first node is considered odd, the second node even and so on ...

 /**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
public class Solution {
    public ListNode oddEvenList(ListNode head) {
        if (head == null) return null;
        ListNode odd = head, even = head.next, evenHead = even;
        while (even != null && even.next != null) {
            odd.next = even.next;
            odd = odd.next;
            even.next = odd.next;
            even = even.next;
        }
        odd.next = evenHead;
        return head;
    }
}


The main idea behind this problem to solve is, put the odd nodes in a linked list and the even nodes in another. Then link the evenList to the tail of the oddList.

1) The head and odd variable are head and tail pointer of odd linked list.
2) The evenHead and even variable are head and tail pointer of even linked list.
3) Then iterate all nodes,
 a) Put odd nodes to odd linked list
 b) Put even nodes to even linked list
4) Variables odd & even are used for iterating through linked list.

Time Complexity: O(N)
Space Complexity: O(1)

The best way of solving any linked list problem is to visualize it either in your mind or on a piece of paper. Here it is somewhat hard to visualize. So, take a paper and just follow the above steps, then you will have clear understanding behind this solving method.

Related Posts:

Click here for May month challenges with solution and explanation
Click here for April month challenges with solution and explanation


Please let us know your views in comment section

Subscribe us to receive updates instantly..

Share with your friends and help us to grow..

Happy Coding..!!

Comments

Popular posts from this blog

Balanced Binary Tree

First Unique Character in a String

Majority Element

Smallest Range II