//linked list
implementation in C
//insert at
beginning
//displaing
elements
//sort the
elements in ascending order
#include<stdio.h>
#include<malloc.h>
void insert(int d);
void display();
void sortAscend();
struct node
{
int data;
struct node *next;
};
struct node *start;
int main()
{
start=NULL;//starting
with empty list
insert(10);//first
element
insert(15);
insert(12);
insert(1);
insert(99);//last
element
printf("\nOriginal
List was:\n");
display();
sortAscend();
return 0;
}
void insert(int d)
{
struct node
*newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=d;
newnode->next=start;
start=newnode;
}
void display()
{
struct node
*ptr=start;
while(ptr!=NULL)
{
printf("%d\t",ptr->data);
ptr=ptr->next;
}
printf("\n");
}
void sortAscend()
{
struct node
*ptr1;
struct node
*ptr2;
int temp;
if(start==NULL)
{
printf("List
is empty.\n");
}
else
{
for
(ptr1=start; ptr1; ptr1=ptr1->next)
{
for
(ptr2=ptr1->next; ptr2; ptr2=ptr2->next)
{
if
(ptr1->data > ptr2->data)
{
temp = ptr1->data;
ptr1->data = ptr2->data;
ptr2->data = temp;
}
}
}
printf("\nSorted List is:\n");
for
(ptr1=start; ptr1!=NULL; ptr1=ptr1->next)
{
printf("%d\t", ptr1->data);
}
}
printf("\n");
}
/*
Original List was:
99 1 12 15 10
Sorted List is:
1 10 12 15 99
*/
No comments:
Post a Comment