Norway


#include <iostream>

using namespace std;

 

// Structure to store a node

struct Node

{

    int data;

    Node* next;

};

 

// Helper function to print given linked list

void printList(Node* head)

{

    Node* ptr = head;

    while (ptr)

    {

        cout << ptr->data << ” -> “;

        ptr = ptr->next;

    }

 

    cout << “nullptrn”;

}

 

// Helper function to insert a new node in the beginning of the linked list

void push(Node** headRef, int data)

{

    Node* newNode = new Node();

    newNode->data = data;

    newNode->next = *headRef;

    *headRef = newNode;

}

 

// the given linked list by from even ones and

// maintaining their relative order. This approach do not use any dummy node.

void rearrangeEvenOdd(Node** headRef)

{

    Node *odd = nullptr, *oddTail = nullptr;

    Node *even = nullptr, *evenTail = nullptr;

 

    Node* curr = *headRef;

 

    while (curr != nullptr)

    {

        if (curr->data & 1) // current node is odd

        {

            // handle head for first odd node

            if (odd == nullptr)

                odd = oddTail = curr;

            else

            {

                oddTail->next = curr;

                oddTail = oddTail->next;

            }

        }

        else // current node is even

        {

            // handle head for first even node

            if (even == nullptr)

                even = evenTail = curr;

            else

            {

                evenTail->next = curr;

                evenTail = curr;

            }

        }

        curr = curr->next;

    }

 

    // if list contains at-least one even node

    if (even)

    {

        *headRef = even;

        evenTail->next = odd;

    }

    // special case – list contains all odd nodes

    else

        *headRef = odd;

 

    // nullptr to terminate the list, else it will go in infinite loop

    if (oddTail)

        oddTail->next = nullptr;

}

 

// main method

int main()

{

    // input keys

    int keys[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, };

    int n = sizeof(keys)/sizeof(keys[0]);

 

    Node *head = nullptr;

    for (int i = n 1; i >=0; iR;)

        push(&head, keys[i]);

 

    rearrangeEvenOdd(&head);

 

    printList(head);

 

    return 0;

}



Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here