Group Odd & Even nodes of Linked List | Linked List Problem

4 years ago Lalit Bhagtani 0

Problem Statement

You have given a singly linked list, group all the nodes at odd places followed by the nodes at even places. Try to do it in-place.

Example 

Linked List

Input :- head = [5, 4, 10, 15, 1]
Output :- [5, 10, 1, 4, 15]
Input :- head = [5, 4, 10, 15, 1, 5, 6]
Output :- [5, 10, 1, 6, 4, 15, 5]

Solution

Create two variables odd and even, odd points to the first node of the linked list and even points to the second node of the linked list. Now move the odd and even variables together till one of them reaches the last node of a linked list. At each move, assign the next value of odd.next node to the odd.next variable and next value of even.next node to the even.next variable.

Program

public class Main {

	public static void main(String[] args) {
		
		ListNode head = null;
		
		ListNode node = new ListNode(5);
		head = node;		
		node.next = new ListNode(4);
		node = node.next;		
		node.next = new ListNode(10);
		node = node.next;		
		node.next = new ListNode(15);
		node = node.next;		
		node.next = new ListNode(1);
		node = node.next;
		node.next = new ListNode(5);
		node = node.next;
		node.next = new ListNode(6);
		
		Main main = new Main();
		ListNode listNodes = main.oddEvenList(head);
		
		while(listNodes != null) {
			System.out.print(listNodes.value + ", ");
			listNodes = listNodes.next;
		}
	}
	
	/* Solution */
	public ListNode oddEvenList(ListNode head) {
        
        if(head != null && head.next != null){
            ListNode odd = head;
            ListNode even = head.next; 
            ListNode temp = even;

            while(odd.next != null && even.next != null){

                if(odd.next.next != null){
                    odd.next = odd.next.next;
                    odd = odd.next;
                }

                if(even.next.next != null){
                    even.next = even.next.next;
                    even = even.next;
                }else {
                    even.next = null;
                }     
            }
            odd.next = temp;
        }        
        return head;
    }
	
	/* Definition of Linked List Node */
	public static class ListNode {		
		int value;
		ListNode next;
		
		public ListNode(int value) {
			this.value = value;
		}		
	}
}

Result

5, 10, 1, 6, 4, 15, 5,

That’s all for Group Odd & Even nodes of Linked List in Java, If you liked it, please share your thoughts in a comments section and share it with others too.