shiv@ubuntu:~/ds/list$ cat tarr_to_sortlist.c
/*
* Program to create sorted list from given unsorted array
*/
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define MAX 10
struct list {
int d;
struct list *next;
};
int main()
{
/* example array to test program */
int a[MAX]={4,1,5,6,10,9,3,2,7,8};
int i;
struct list *head=NULL, *temp, *insert;
/*loop to get all array elements*/
for(i=0;i<MAX;i++) {
temp= malloc(sizeof(struct list));
if (temp == NULL) {
printf("Can't allocate memory\n");
exit(0);
}
temp->d = a[i];
temp->next = NULL;
/* first node in list */
if( head == NULL) {
head = temp;
} else {
/* second node in the list */
if( head->next == NULL){
if(head->d > temp->d){
temp->next = head;
head= temp;
} else {
head->next = temp;
}
continue;
}
insert = head;
/* we need to stop at node before the greater value node,
to insert new node before it, at single linked list,
if you stop at greater value node and want insert before it,
it is not possible directly so it is insert->next->d
*/
while(insert->next && (insert->next->d < temp->d)) {
if(insert->next->next == NULL)
break;
insert=insert->next;
}
/* as list is sorted until if new element last insert->next->d
* is less than the current node to be inserted, current is next last node
*/
if((insert->next->next == NULL) && (insert->next->d < temp->d)) {
insert=insert->next;
insert->next = temp;
} else {
/* insert after the current node */
temp->next = insert->next;
insert->next = temp;
}
}
}
printf("The sorted list is \n");
/* to display values in list to test program is working? */
while(head !=NULL){
printf("%d\n", head->d);
head= head->next;
}
}
/* end of the program */
sample out of the program below
Comments
Post a Comment