I am trying to solve this problem. The problem is to sort a linked list containing only 0s, 1s and 2s by changing their links.
Sort a linked list of 0s, 1s and 2s by changing links Given a linked list of 0s, 1s and 2s, sort it.
Examples:
Input : 2->1->2->1->1->2->0->1->0 Output : 0->0->1->1->1->1->2->2->2
Input : 2->1->0 Output : 0->1->2
Here is my code:
#include <stdio.h>
#include <stdlib.h>
typedef struct node* Node;
struct node
{
int data;
struct node* next;
};
void addnode(Node* head, int data)
{
Node temp = (Node)malloc(sizeof(struct node));
temp->data = data;
temp->next = NULL;
if( *head == NULL )
{
*head = temp;
return;
}
Node p =(Node)malloc(sizeof(struct node));
p = *head;
while( p->next != NULL )
{
p = p->next;
}
p->next = temp;
}
void display(Node head)
{
Node p =(Node)malloc(sizeof(struct node));
p = head;
while( p != NULL )
{
printf("%d ", p->data);
p = p->next;
}
}
void zeroonetwo(Node* head)
{
if( *head == NULL )
{
return;
}
Node zero = (Node)malloc(sizeof(struct node));
Node one = (Node)malloc(sizeof(struct node));
Node two = (Node)malloc(sizeof(struct node));
zero = NULL;
one = NULL;
two = NULL;
Node p = (Node)malloc(sizeof(struct node));
p = *head;
Node temp1 = (Node)malloc(sizeof(struct node));
Node temp2 = (Node)malloc(sizeof(struct node));
Node temp3 = (Node)malloc(sizeof(struct node));
temp1 = NULL;
temp2 = NULL;
temp3 = NULL;
while( p != NULL )
{
if( p->data == 0 )
{
if( temp1 == NULL )
{
temp1 = p;
zero = temp1;
}
else
{
temp1->next = p;
temp1 = temp1->next;
}
}
else if( p->data == 1 )
{
if( temp2 == NULL )
{
temp2 = p;
one = temp2;
}
else
{
temp2->next = p;
temp2 = temp2->next;
}
}
else
{
if( temp3 == NULL )
{
temp3 = p;
two = temp3;
}
else
{
temp3->next = p;
temp3 = temp3->next;
}
}
p = p->next;
}
if( zero != NULL && one != NULL && two != NULL )
{
*head = zero;
temp1->next = one;
temp2->next = two;
temp3->next = NULL;
}
else if( zero == NULL && one != NULL && two != NULL )
{
*head = one;
temp2->next = two;
temp3->next = NULL;
}
else if( zero == NULL && one == NULL && two != NULL )
{
*head = two;
temp3->next = NULL;
}
else if( zero != NULL && one == NULL && two != NULL )
{
*head = zero;
temp1->next = two;
temp3->next = NULL;
}
else if( zero != NULL && one == NULL && two == NULL )
{
*head = zero;
temp1->next = NULL;
}
else if( zero == NULL && one != NULL && two == NULL )
{
*head = one;
temp2->next = NULL;
}
else
{
*head = zero;
temp1->next = one;
temp2->next = NULL;
}
}
int main()
{
int N;
scanf("%d", &N);
Node head = (Node)malloc(sizeof(struct node));
head = NULL;
for(int i = 0; i < N; i++)
{
int data;
scanf("%d", &data);
addnode(&head, data);
}
zeroonetwo(&head);
display(head);
}
But I believe the code can be shortened. The 8 checks to check NULL for zero, one and two seem redundant. I would really appreciate if you someone could provide me suggestions and point any bugs if any exist.
splice
,insert_front
, andinsert_back
functions and the code would be very simple and elegant. \$\endgroup\$