Last active
October 6, 2016 19:12
-
-
Save priyadarshitathagat/a6e7d7f7533bd619ede6fdaa442030ef to your computer and use it in GitHub Desktop.
Sorting of linked list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//sorting the elements of a linked list by selection sort technique | |
#include <stdio.h> | |
#include<stdlib.h> | |
struct node | |
{ | |
int val; | |
struct node *link; | |
}; | |
struct node* getnode( ) | |
{ | |
return ( struct node *)malloc( sizeof( struct node )); | |
}; | |
struct node* acc( struct node *); struct node* sortit(struct node *); | |
void display( struct node *); | |
int x; | |
int main() | |
{ | |
struct node *F; | |
int ch,i; | |
F = NULL; | |
printf("Enter number of elements to be entered in the list :\n"); | |
scanf("%d",&x); | |
for(i=0; i<x; i++) | |
{ | |
F = acc(F); | |
} | |
printf("List before sorting :\n"); | |
display(F); | |
F=sortit(F); | |
printf("List after sorting :\n"); | |
display(F); | |
} | |
struct node* acc(struct node *FIRST) | |
{ | |
struct node *T; | |
if( FIRST == NULL ) | |
{ | |
FIRST = getnode(); | |
T = FIRST; | |
} | |
else | |
{ | |
T = FIRST; | |
while( T->link != NULL ) T = T->link; | |
T->link = getnode( ); | |
T = T->link; | |
} | |
scanf("%d", &T->val); | |
T->link = NULL; | |
return FIRST; | |
} | |
struct node* sortit(struct node *X) | |
{ struct node *T; T=X; struct node *P; int c; | |
if(X==NULL) | |
{ return(X); } | |
while(T!=NULL) | |
{ P=T->link; | |
while(P!=NULL) | |
{ | |
if(T->val>P->val) | |
{ | |
c=P->val; P->val=T->val; T->val=c; | |
} | |
P=P->link; | |
} | |
T=T->link; | |
} | |
return(X); | |
} | |
void display( struct node *T) | |
{ | |
while( T!= NULL ) | |
{ | |
printf("%d ",T->val); | |
T = T->link; | |
} | |
printf("\n"); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment