DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Odd-even LinkedList

Problem

We have to keep index i tracking the node values if i is odd then put them in a different say odd, else put them in a list say even.
At the end connect the last node of the odd list to head of even list

/**
 * 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; }
 * }
 */
class Solution {
    public ListNode oddEvenList(ListNode head) {
        ListNode odd  = new ListNode(0);
        ListNode even = new ListNode(0);
        ListNode pointerOfOdd = odd;
        ListNode pointerOfEven = even;
        int i =1;
        while(head!=null){
            if(i%2!=0){
                odd.next = new ListNode(head.val);
                odd = odd.next;
            }
            else{
                even.next = new ListNode(head.val);
                even = even.next;
            }
            i++;
            head = head.next;
        }
        odd.next = pointerOfEven.next;

        return pointerOfOdd.next;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.