Advertisement
Guest User

9

a guest
Nov 15th, 2019
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. #include <stdio.h>
  2. #include<stdlib.h>
  3. #include<string.h>
  4. typedef struct node
  5. {
  6. int info;
  7. struct node *next;
  8. }NODE;
  9. NODE *insert(NODE *first,int data)
  10. {
  11. NODE *newnode,*temp,*prev;
  12. newnode=(NODE*)malloc(sizeof(NODE));
  13. newnode->info=data;
  14. if(first==NULL || data<first->info)
  15. {
  16. newnode->next=first;
  17. first=newnode;
  18. }
  19. else
  20. {
  21. temp=first;
  22. while(temp!=NULL && data>temp->info)
  23. {
  24. prev=temp;
  25. temp=temp->next;
  26. }
  27. if(temp==NULL || data!=temp->info)
  28. {
  29. prev->next=newnode;
  30. newnode->next=temp;
  31. }
  32. }
  33. return first;
  34. }
  35. void display(NODE *first)
  36. {
  37. if(first==NULL)
  38. {
  39. printf("Empty");
  40. return;
  41. }
  42. printf("Contents:\nBegin->");
  43. while(first!=NULL)
  44. {
  45. printf("%d->",first->info);
  46. first=first->next;
  47. }
  48. printf("End");
  49. }
  50. NODE *merge(NODE *L1,NODE *L2,NODE *L3)
  51. {
  52. L3=NULL;
  53. if(L1==NULL && L2==NULL)
  54. {
  55. printf("\nEMPTY LISTS");
  56. return NULL;
  57. }
  58. while(L1!=NULL && L2!=NULL)
  59. {
  60. if(L1->info<L2->info)
  61. {
  62. L3=insert(L3,L1->info);
  63. L1=L1->next;
  64. }
  65. else if(L2->info<L1->info)
  66. {
  67. L3=insert(L3,L2->info);
  68. L2=L2->next;
  69. }
  70. else
  71. {
  72. L3=insert(L3,L1->info);
  73. L1=L1->next;
  74. L2=L2->next;
  75. }
  76. }
  77. while(L1!=NULL)
  78. {
  79. L3=insert(L3,L1->info);
  80. L1=L1->next;
  81. }
  82. while(L2!=NULL)
  83. {
  84. L3=insert(L3,L2->info);
  85. L2=L2->next;
  86. }
  87. printf("\nLists are merged successfully");
  88. printf("\nList3 ");
  89. display(L3);
  90. return L3;
  91. }
  92. int main()
  93. {
  94. NODE *L1=NULL,*L2=NULL,*L3=NULL;
  95. int data,choice;
  96. while(1)
  97. {
  98. printf("\n1:INS_LIST1\n2:INS_LIST2\n3:MERGE\nDISPLAY");
  99. printf("\nEnter your choice: ");
  100. scanf("%d",&choice);
  101. switch(choice)
  102. {
  103. case 1: printf("\nEnter the data: ");
  104. scanf("%d",&data);
  105. L1=insert(L1,data);
  106. break;
  107. case 2: printf("\nEnter the data: ");
  108. scanf("%d",&data);
  109. L2=insert(L2,data);
  110. break;
  111. case 3: L3=merge(L1,L2,L3);
  112. break;
  113. case 4: printf("\nList1 ");
  114. display(L1);
  115. printf("\nList2 ");
  116. display(L2);
  117. break;
  118. case 5: exit(0);
  119. default: printf("\nInvalid choice");
  120. }
  121. }
  122. return 0;
  123. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement