Monday, June 11, 2012

Sorting program on linked list


In this program a linked list will be created first and after that the linked list will be sorted in ascending in ascending order according to values in nodes.

How to proceed in this linked list sorting program

Create a linked list using a do while loop and assign values to the information part variable of the nodes. Create the first node of the linked list in the main () function and the other nodes are to be created inside a function ‘void create (struct link *)’.

Use another function ‘void sort (struct tag *)’ where selection sort technique can be used for sorting the elements of the linked list according to their values.

The third function ‘void display (struct tag *)’ in this program will display the value of the nodes in the linked list.

After creating the linear linked list, display the list and again display after sorting the elements.

Here are the programming codes of the program

# include < stdio.h>
# include < stdlib.h>
struct link
{
int info;
struct link *next;
};
int i;
int number;
struct link *p,*node;
void create(struct link *n)
{
char ch;
i=1;
node=n;
printf("\n Enter value for node: %d: ",i);
scanf("%d", &node->info);
fflush(stdin);
node->next = NULL;
do
{
i=i+1;
node->next = (struct link* ) malloc(sizeof(struct link));
node = node->next;
printf("\n Enter value for node: %d: ",i);
scanf("%d", &node->info);
node->next = NULL;
printf("\n Input choice n for break: ");
ch = getche();
} while(ch != 'n');

printf("\n Total nodes = %d", i);
}
void display(struct link *n)
{
node = n;
while (node)
{
printf(" %d", node->info);
node = node->next;
}
}
void sort(struct link *n)
{
int t;
p=n;
while(p)
{
node=p->next;
while(node)
{
if(p->info>node->info)
{
t=p->info;
p->info=node->info;
node->info=t;
}
node=node->next;
}
p=p->next;
}
}
void main()
{
struct link *start;
clrscr();
start=(struct link *)malloc(sizeof(struct link));
create(start);
printf("\n Created list is as follows:\n");
display(start);
sort(start);
printf("\n After sorting,list is as follows:\n");
display(start);
getch();
}

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner