Odd Even Linked List - Medium - NL

1 minute read

Published:

Question

  • https://leetcode.com/problems/odd-even-linked-list/

Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.

The first node is considered odd, and the second node is even, and so on.

Note that the relative order inside both the even and odd groups should remain as it was in the input.

Approach

  • iterative

Solution

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        if(head == NULL || head->next==NULL || head->next->next==NULL) {
            return head;
        }
        ListNode* prev = NULL;
        ListNode* prev1 = NULL;
        ListNode* temp = head;
        ListNode* temp1 = NULL;
        int co=1;
        while(temp!=NULL) {
            if(co==1) {
                temp = head;
                temp1 = head->next;
                prev = head;
                prev1 = temp1;
            } else {
                prev->next = temp;
                prev = temp;
                cout<<prev1->val<<endl;
                if(temp->next!=NULL) {
                    prev1->next = temp->next;
                    prev1 = temp->next;
                } else {
                    prev->next=NULL;
                    break;
                }
            }
            temp = temp->next->next;
            co++;
        }
        prev1->next = NULL;
        temp = prev;
        temp->next = temp1;
        return head;
    }
};