Given a Linked List of integers, write a function to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. Also, keep the order of even and odd numbers same.
Examples:
Input: 17->15->8->12->10->5->4->1->7->6->NULL
Output: 8->12->10->4->6->17->15->5->1->7->NULL
Input: 8->12->10->5->4->1->6->NULL
Output: 8->12->10->4->6->5->1->NULL
// If all numbers are even then do not change the list
Input: 8->12->10->NULL
Output: 8->12->10->NULL
// If all numbers are odd then do not change the list
Input: 1->3->5->7->NULL
Output: 1->3->5->7->NULL
#include "linkedlist.h"
#include
NODE* createLL(int maxNode)
{
int index;
NODE* headNode=NULL;
for (index = 0; index <= maxNode; index++)
{
headNode = addAtHead(headNode, rand()%100);
}
return headNode;
}
NODE* segregateEvenOdd(NODE* headNode)
{
NODE* currentNode = headNode;
NODE* lastNode = headNode;
NODE* previousNode = NULL;
int length = 0;
/* Find lastNode and length */
while(currentNode != NULL)
{
lastNode = currentNode;
currentNode = currentNode->next;
length++;
}
currentNode = headNode;
while(length)
{
/* push OddNumber node to last */
if (currentNode->data % 2 == 1)
{
if (headNode != currentNode)
{
previousNode->next = currentNode->next;
lastNode->next = currentNode;
lastNode = currentNode;
currentNode->next = NULL;
currentNode = previousNode->next;
}
else
{
lastNode->next = headNode;
lastNode = headNode;
headNode = headNode->next;
currentNode->next = NULL;
currentNode = headNode;
}
}
else
{
previousNode = currentNode;
currentNode = currentNode->next;
}
length--;
}
return headNode;
}
/* Driver program */
int main()
{
NODE* headNode=createLL(10);
printList(headNode);
headNode = segregateEvenOdd(headNode);
printList(headNode);
}
|
No comments:
Post a Comment