1. Write a C code to split the original single linked list into two sub-lists, where the first and second sub-list contains the even position nodes and odd position nodes of the original list respectively, and then join the second sub-list at the end of the first sub-list. Example: If the list contains 3->4->2->1->7->9->8, then the function needs to produce 3->2->7->8->4->1->9.
#include<stdio.h>
#include<stdlib.h>
struct ListNode
{
int data;
struct ListNode *nextNode;
};
typedef struct ListNode Node;
Node* oddEvenList(Node* head)
{
Node* temp = head;
Node* oddNode = NULL,*odd = NULL;
Node* even = NULL, *evenNode = NULL;
while( temp != NULL)
{
if(!(temp->data%2))
{
if(even == NULL)
even = temp;
else
evenNode->nextNode = temp;
evenNode = temp;
}
else
{
if(odd == NULL)
odd = temp;
else
oddNode->nextNode = temp;
oddNode = temp;
}
temp = temp->nextNode;
}
head = odd;
oddNode->nextNode = even;
evenNode->nextNode = NULL;
return head;
}
Node* add(Node *head, int item)
{
Node *temp=head;
Node *node = (Node*)malloc(sizeof(Node));
node->data = item;
node->nextNode = NULL;
if(temp == NULL)
{
head=node;
}
else if(temp->nextNode==NULL)
{
temp->nextNode = node;
}
else
{
Node *temp = head;
while(temp->nextNode != NULL)
{
temp = temp->nextNode;
}
temp->nextNode = node;
}
return head;
}
void printList(Node *head)
{
Node *tempNode = head;
while (tempNode->nextNode !=NULL)
{
printf("%d->",tempNode->data);
tempNode = tempNode->nextNode;
}
printf("%d\n",tempNode->data);
}
int main()
{
Node *node = NULL;
int x;
for (x=1;x<20;x++)
{
node = add(node,x);
}
printList(node);
node=oddEvenList(node);
printList(node);
}
Comments
Leave a comment