Rearrange a linked list in such a way that all odd position nodes are together and all even positions node are together,
Examples:
Input: 1->2->3->4
Output: 1->3->2->4
Input: 10->22->30->43->56->70
Output: 10->30->56->22->43->70
The important thing in this question is to make sure that all below cases are handled
- Empty linked list.
- A linked list with only one node.
- A linked list with only two nodes.
- A linked list with an odd number of nodes.
- A linked list with an even number of nodes.
The below program maintains two pointers ‘odd’ and ‘even’ for current nodes at odd and even positions respectively. We also store the first node of the even linked list so that we can attach the even list at the end of the odd list after all odd and even nodes are connected together in two different lists.
C
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node* next;
};
Node* newNode( int key)
{
Node *temp = new Node;
temp->data = key;
temp->next = NULL;
return temp;
}
Node *rearrangeEvenOdd(Node *head)
{
if (head == NULL)
return NULL;
Node *odd = head;
Node *even = head->next;
Node *evenFirst = even;
while (1)
{
if (!odd || !even || !(even->next))
{
odd->next = evenFirst;
break ;
}
odd->next = even->next;
odd = even->next;
if (odd->next == NULL)
{
even->next = NULL;
odd->next = evenFirst;
break ;
}
even->next = odd->next;
even = odd->next;
}
return head;
}
void printlist(Node * node)
{
while (node != NULL)
{
cout << node->data << "->" ;
node = node->next;
}
cout << "NULL" << endl;
}
int main( void )
{
Node *head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(3);
head->next->next->next = newNode(4);
head->next->next->next->next = newNode(5);
cout << "Given Linked List" ;
printlist(head);
head = rearrangeEvenOdd(head);
cout << "Modified Linked List" ;
printlist(head);
return 0;
}
|
Output:
Given Linked List
1->2->3->4->5->NULL
Modified Linked List
1->3->5->2->4->NULL
Time Complexity: O(n) where n is the number of nodes in the given linked list.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Please refer complete article on Rearrange a linked list such that all even and odd positioned nodes are together for more details!
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
22 Jun, 2022
Like Article
Save Article