/*How to Merge two Sorted Linked List using C*/
#include<stdio.h> //List1 typedef struct mynode1 { int info; struct mynode1 *Link; }Node1; Node1* mymerged(Node1*, Node1*); Node1 *start1=NULL,*start2=NULL,*mergedlist=NULL; void mergeddisplay(Node1*); void mergeddisplay(Node1* ptr) { Node1 *tptr=ptr; printf("merged list:\n"); if (tptr == NULL) printf("merged list is NULL"); while(tptr!=NULL) { printf("->"); printf("%d",tptr->info); tptr=tptr->Link; } } //Display Function void display() { Node1 *tptr1=start1,*tptr2=start2; printf("\nList1:\n"); while(tptr1) { printf("->%d",tptr1->info); tptr1=tptr1->Link; } printf("\nList2:\n"); while(tptr2) { printf("->%d",tptr2->info); tptr2=tptr2->Link; } printf("\n"); } Node1* mymerged(Node1 *start1, Node1 *start2) { Node1 *ptr1,*ptr2,*third=NULL,*ptr,*cptr; ptr1=start1; ptr2=start2; if (ptr1 == NULL) { return ptr2; } if (ptr2 == NULL) { return ptr1; } if(ptr1!=NULL && ptr2!=NULL) { if(ptr1->info<=ptr2->info) { third=ptr1; ptr1=ptr1->Link; } else { third=ptr2; ptr2=ptr2->Link; } } ptr=third; while(ptr1!=NULL && ptr2!=NULL) { if(ptr1->info<=ptr2->info) { ptr->Link=ptr1; ptr1=ptr1->Link; } else { ptr->Link=ptr2; ptr2=ptr2->Link; } ptr=ptr->Link; } if(ptr1 != NULL) { ptr->Link=ptr1; } if(ptr2 != NULL) { ptr->Link=ptr2; } return third; } //Isertion List1 void add_node_List1(int value1) { Node1 *newp=NULL,*tptr=NULL; newp=(Node1*)malloc(sizeof(Node1)); newp->info=value1; newp->Link=NULL; if(start1==NULL) { start1=newp; } else { tptr=start1; while(tptr->Link!=NULL) { tptr=tptr->Link; } tptr->Link=newp; } } //Isertion List2 void add_node_List2(int value2) { Node1 *newp=NULL,*tptr=NULL; newp=(Node1*)malloc(sizeof(Node1)); newp->info=value2; newp->Link=NULL; if(start2==NULL) { start2=newp; } else { tptr=start2; while(tptr->Link!=NULL) { tptr=tptr->Link; } tptr->Link=newp; } } int main() { char ch1,ch2; int value1,value2; //For List1 printf("Enter first list:-\n"); while(1) { printf("Enter Y to add a node or N to exit:"); scanf("%c",&ch1); fflush(stdin); if(ch1=='Y'||ch1=='y') { printf("Enter the info:"); scanf("%d",&value1); fflush(stdin); add_node_List1(value1); printf("Node Inserted\n"); } else { break; } } //For List2 printf("Enter second list:-\n"); while(1) { printf("Enter Y to add a node or N to exit:"); scanf("%c",&ch2); fflush(stdin); if(ch2=='Y'||ch2=='y') { printf("Enter the info:"); scanf("%d",&value2); fflush(stdin); add_node_List2(value2); printf("Node Inserted\n"); } else { break; } } display(); //display_merge(); mergedlist=mymerged(start1,start2); mergeddisplay(mergedlist); return 0; }
Comentarios