An ascending order linked list is the list sorted in increasing order of data. During addition one needs to traverse the list until the element having data value same or higher is not found and then, create the node and insert it there.
The following C program builds a linked list in ascending order.
The following C program builds a linked list in ascending order.
//ascending order linked list /** * *@author VIKASH VIK VIKASHVVERMA * */ #include<stdio.h> #include<stdlib.h> typedef struct node { int data; struct node*next; }node; void add(node**s,int num) { node*temp; if(*s==NULL||num<(*s)->data) { temp=(node*)malloc(sizeof(node)); temp->data=num; temp->next=*s; *s=temp; } else { temp=*s; while(temp!=NULL) { if(temp->data<=num&&(temp->next==NULL || temp->next->data>num)) { node*temp1=(node*)malloc(sizeof(node)); temp1->data=num; temp1->next=temp->next; temp->next=temp1; return; } temp=temp->next; } } } void traverse(node*s) { while(s!=NULL) { printf("%d\t",s->data); s=s->next; } } void main() { node*n=NULL; add(&n,5); add(&n,7); add(&n,18); add(&n,12); add(&n,78); add(&n,-13); traverse(n); }
No comments :
Post a Comment