fork(2) download
  1. #include <iostream>
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. using namespace std;
  5. struct node
  6. {
  7. int data;
  8. struct node* next;
  9. };
  10. void push(struct node** head_ref, int new_data)
  11. {
  12. /* allocate node */
  13. struct node* new_node =
  14. (struct node*) malloc(sizeof(struct node));
  15.  
  16. /* put in the data */
  17. new_node->data = new_data;
  18.  
  19. /* link the old list off the new node */
  20. new_node->next = (*head_ref);
  21.  
  22. /* move the head to point to the new node */
  23. (*head_ref) = new_node;
  24. }
  25. void printList(struct node *node)
  26. {
  27. while(node!=NULL)
  28. {
  29. printf("%d ", node->data);
  30. node = node->next;
  31. }
  32. }
  33. struct node* merge(struct node*a,struct node*b){
  34. struct node* c=NULL;
  35. struct node* temp1=NULL;
  36. while(a||b){
  37. if(a==NULL)
  38. {if(c==NULL)
  39. return b;
  40. else{
  41. temp1->next=b;
  42. break;
  43. }
  44.  
  45. }
  46. else if(b==NULL)
  47. {if(c==NULL)
  48. return a;
  49. else
  50. temp1->next=a;
  51. break;
  52. }
  53. struct node* temp=(struct node*)malloc(sizeof(struct node));
  54. if(a->data<=b->data){
  55. temp->data=a->data;
  56. temp->next=NULL;
  57. a=a->next;
  58. }
  59. else{
  60. temp->data=b->data;
  61. temp->next=NULL;
  62. b=b->next;
  63. }
  64. if(c==NULL)
  65. {
  66. c=temp;
  67. temp1=c;
  68. }
  69. else{
  70. temp1->next=temp;temp1=temp;
  71. }
  72. }
  73. return c;
  74. }
  75. int main()
  76. {
  77.  
  78. struct node* a = NULL;
  79. struct node* b = NULL;
  80. struct node* c=NULL;
  81. push(&a, 15);
  82. push(&a, 10);
  83. push(&a, 5);
  84.  
  85. push(&b, 20);
  86. push(&b, 3);
  87. push(&b, 2);
  88.  
  89. c= merge(a, b);
  90.  
  91. printf("\n Merged Linked List is: \n");
  92. printList(c);
  93.  
  94. getchar();
  95. return 0;
  96. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
 Merged Linked List is: 
2 3 5 10 15 20