fork download
  1. #include <stdio.h>
  2.  
  3. // Given two sorted linked lists and merge them in sorted order.
  4. struct Node
  5. {
  6. int data;
  7. struct Node *next;
  8. };
  9.  
  10. void printList(struct Node *head)
  11. {
  12. struct Node *curr = head;
  13. while (curr != NULL)
  14. {
  15. printf("%d ", curr->data);
  16. curr = curr->next;
  17. }
  18. printf("\n");
  19. }
  20. struct Node *mergeSortedNodes(struct Node *first,
  21. struct Node *second)
  22. {
  23. if (first == NULL)
  24. {
  25. return second;
  26. }
  27. else if (second == NULL)
  28. {
  29. return first;
  30. }
  31. struct Node *top;
  32. struct Node *curr;
  33. if (first->data < second->data)
  34. {
  35. top = curr = first;
  36. first = first->next;
  37. }
  38. else
  39. {
  40. top = curr = second;
  41. second = second->next;
  42. }
  43. while (first != NULL && second != NULL)
  44. {
  45. if (first->data < second->data)
  46. {
  47. curr->next = first;
  48. first = first->next;
  49. }
  50. else
  51. {
  52. curr->next = second;
  53. second = second->next;
  54. }
  55. curr = curr->next;
  56. }
  57. if (first != NULL)
  58. {
  59. while (first != NULL)
  60. {
  61. curr->next = first;
  62. first = first->next;
  63. curr = curr->next;
  64. }
  65. }
  66. if (second != NULL)
  67. {
  68. while (second != NULL)
  69. {
  70. curr->next = second;
  71. second = second->next;
  72. curr = curr->next;
  73. }
  74. }
  75. return top;
  76. }
  77. struct Node *newNode(int data)
  78. {
  79. struct Node *tmp = (struct Node *)malloc(sizeof(struct Node));
  80. tmp->data = data;
  81. tmp->next = NULL;
  82. return tmp;
  83. }
  84. int main()
  85. {
  86. struct Node *first = newNode(10);
  87. first->next = newNode(20);
  88. first->next->next = newNode(30);
  89. first->next->next->next = newNode(40);
  90. first->next->next->next->next = newNode(50);
  91.  
  92. struct Node *second = newNode(5);
  93. second->next = newNode(8);
  94. second->next->next = newNode(13);
  95. second->next->next->next = newNode(37);
  96.  
  97. printList(first);
  98. printList(second);
  99. struct Node *mergeNode = mergeSortedNodes(first, second);
  100. printList(mergeNode);
  101. printList(first);
  102. printList(second);
  103. }
Success #stdin #stdout 0s 4340KB
stdin
Standard input is empty
stdout
10 20 30 40 50 
5 8 13 37 
5 8 10 13 20 30 37 40 50 
10 13 20 30 37 40 50 
5 8 10 13 20 30 37 40 50