Sorting the Linked List

Previous
Next
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct node
{
	int data;
	struct node *link;
};
struct node* root = NULL ;
void create(void);
void sort(void);
void display(void);
int count=0;
void main()
{
	int ch , len ;
	while(1)
	{
		printf("\n/**Single linked list Operations**/\n");
		printf("1.Create \n");
		printf("2.Sort List \n");
		printf("3.Display \n");
		printf("4.Quit \n");
		printf("Enter Choice : ");
		scanf("%d", &ch);

		switch(ch)
		{
			case 1	:	create();
						break;

			case 2	:	sort();
						break;

			case 3	:	display();
						break;

			case 4	:	exit(0);

			default	:	printf("Invalid choice....\n\n");
		}
	}
}

void create()
{
	struct node *temp,*p;
	temp = root ;
	while(1)
	{
		p=(struct node *)malloc(sizeof(struct node));
		printf("Enter data :");
		scanf("%d", &p->data);
		count++;
		if(root==NULL)
		{
			root = p;
			p->link = NULL;
			temp = p;
		}
		else
		{
			temp->link=p;
			temp=p;
		}
		printf("Do you want to stop(y/n) : ");
		if(getch()=='y')
		{
			break;
		}
	}
	p->link=NULL;
}

void sort()
{
	int i,j,n,temp;
    struct node *p, *q ;
    n=count ;
    for(i=0;i<n-1;i++)
    {
        p=root ;
        q=p->link ;

        for(j=0;j<n-1-i;j++)
        {
            if(p->data > q->data)
            {
                temp = p->data;
                p->data = q->data;
                q->data = temp;
            }
            p=p->link;
            q=q->link;
        }
    }
}

void display()
{
	if(root == NULL)
	{
		printf("List is empty\n\n");
	}
	else
	{
		struct node* temp = root ;
		while(temp != NULL)
		{
			printf("%d \n", temp->data);
			temp = temp->link ;
		}
	}
}
Previous
Next

Add Comment

Courses Enquiry Form