fork download
  1. #include <stdio.h>
  2.  
  3. struct node
  4. {
  5. int data;
  6. struct node* next;
  7. };
  8. struct node *head=NULL;
  9. void push(struct node** head_ref, int new_data)
  10. {
  11. // you should point to NULL
  12. if((*head_ref==NULL))
  13. {
  14. (*head_ref)=malloc(sizeof(struct node));
  15. (*head_ref)->next=NULL;
  16. (*head_ref)->data=new_data; // you are not inserting data
  17. }
  18. else
  19. {
  20. struct node* new_node=malloc(sizeof(struct node));
  21. new_node->next = (*head_ref);
  22. new_node->data=new_data;
  23. (*head_ref) = new_node;
  24. }
  25. }
  26. void printList(struct node *node)
  27. {
  28. while(node!=NULL)
  29. {
  30. printf("%d ", node->data);
  31. node = node->next;
  32. }
  33. }
  34. void move(struct node* temp1,struct node** temp3){
  35. struct node* node1= malloc(sizeof(struct node));
  36. node1->data=temp1->data;
  37. if(*temp3==NULL){
  38. *temp3=node1;
  39. node1->next=NULL;
  40. head=(*temp3);
  41. return;
  42. }
  43. else{
  44. (*temp3)-> next=node1;
  45. (*temp3)=(*temp3)->next;
  46. (*temp3)->next=NULL; // final node should point NULL
  47. }
  48. }
  49.  
  50. void merge(struct node* a,struct node* b,struct node** c){
  51. if(a==NULL){
  52. *c=b;
  53. return;
  54. }
  55. else if(b==NULL){
  56. *c=a;
  57. return;
  58. }
  59. else{
  60. struct node* temp1;
  61. struct node* temp2;
  62. struct node* temp3;
  63. temp1=a;
  64. temp2=b; // main bug in your code is merging is done with temp3 not with (*c) so (*c) always points NULL and it is not printing any data
  65. while(temp1!=NULL && temp2!=NULL)
  66. {
  67. if(temp1->data<temp2->data){
  68. move(temp1,c); // so manpiluating whole program with 'c'
  69. temp1=temp1->next;
  70. }
  71. else{
  72. move(temp2,c);
  73. temp2=temp2->next;
  74. }
  75. }
  76. if(temp1==NULL){
  77. (*c)->next=temp2;
  78. }
  79. else
  80. {
  81. (*c)->next=temp1;
  82. }
  83. }
  84. }
  85. int main()
  86. {
  87.  
  88. struct node* a = NULL;
  89. struct node* b = NULL;
  90. struct node* c = NULL;
  91. push(&a, 15);
  92. push(&a, 10);
  93. push(&a, 5);
  94. push(&b, 20);
  95. push(&b, 3);
  96. push(&b, 2);
  97. merge(a, b,&c);
  98. printList(head); // head is nothing but a global pointer which points to initial node of 'c'
  99. printf("\n");
  100. return 0;
  101. }
  102.  
Success #stdin #stdout 0s 2424KB
stdin
Standard input is empty
stdout
2 3 5 10 15 20