top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Write a C program to Sort a Linked List of 0s, 1s and 2s?

–1 vote
648 views

Given a Singly linked list with each node containing either 0, 1 or 2. Write code to sort the list.
Input : 1 -> 1 -> 2 -> 0 -> 2 -> 0 -> 1 -> 0
Output : 0 -> 0 -> 0 -> 1 -> 1 -> 1 -> 2 -> 2

posted Aug 18, 2016 by Mohammed Hussain

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

0 votes
#include<stdio.h>
#include<stdlib.h>

struct stTest{
        int num;
        struct stTest *next;
};

void FreeMemory(struct stTest *ptr)
{
        while(ptr)
        {
                printf("Freeing Memory\n");
                free(ptr);
                ptr=ptr->next;
        }
}

void AddLinkList(struct stTest **ptr)
{
        struct stTest *tempPtr1=NULL,*tempPtr2=NULL;
        tempPtr1=(struct stTest *)malloc(sizeof(struct stTest));
        if(tempPtr1==NULL)
        {
                printf("Error Allocating Memory\n");
                FreeMemory(*ptr);
                exit(0);
        }
        printf("Enter Number :\n");
        scanf("%d",&tempPtr1->num);
        if((*ptr==NULL) || ((*ptr)->num > tempPtr1->num))
        {
                tempPtr1->next=*ptr;
                *ptr=tempPtr1;
                return;
        }
        tempPtr2=*ptr;
        while(tempPtr2)
        {
                if(tempPtr2->next==NULL)
                {
                        tempPtr1->next=tempPtr2->next;
                        tempPtr2->next=tempPtr1;
                        break;
                }
                else if((tempPtr2->num < tempPtr1->num) && (tempPtr2->next->num > tempPtr1->num))
                {
                        tempPtr1->next=tempPtr2->next;
                        tempPtr2->next=tempPtr1;
                        return;
                }
                tempPtr2=tempPtr2->next;
        }
}

void PrintLinkList(struct stTest *ptr)
{
        while(ptr)
        {
                printf("num = %d\n",ptr->num);
                ptr=ptr->next;
        }
}


main(int argc,char *argv[])
{
        if(argc!=2)
        {
                printf("Usage : Provide Number of link list to be created\n");
                exit(0);
        }
        struct stTest *headPtr=NULL;
        int i=0;
        for(i=0;i<atoi(argv[1]);i++)
                AddLinkList(&headPtr);
        PrintLinkList(headPtr);
        FreeMemory(headPtr);
}
answer Aug 19, 2016 by Chirag Gangdev
0 votes
**/*Here We are using Selection Sort */**

Sort_linked_list(NODE *head)
{
NODE *tmp = NULL;
int N = 0;

while(head)  
{
    tmp = head;
    while(tmp)
    {
        if(head->num > tmp->num)
        {               /* Just Swapping the Contents */
            N = head->num;
            head->num = tmp->num;
            tmp->num = N;
        }
        tmp = tmp -> link;
    }
    head = head ->link;
}

}

answer Sep 8, 2016 by Vinay
...