fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct listNode{
  5. int data;
  6. struct listNode* next;
  7. } typedef listNode;
  8.  
  9. /* Function to print nodes in a given linked list */
  10. void printList(listNode *node){
  11. while(node != NULL){
  12. printf("%d ", node->data);
  13. node = node->next;
  14. }
  15. printf("\n");
  16. }
  17.  
  18. void push(listNode **head, int data){
  19. listNode *temp = (listNode *)malloc(sizeof(listNode));
  20. temp->data = data;
  21. temp->next = *head;
  22. *head = temp;
  23. }
  24.  
  25. /**
  26.  * Definition for singly-linked list.
  27.  * struct ListNode {
  28.  * int val;
  29.  * struct ListNode *next;
  30.  * };
  31.  */
  32. struct listNode* mergeTwoLists(struct listNode* a, struct listNode* b) {
  33. struct listNode* result = NULL;
  34. /* Base cases */
  35. if (a == NULL)
  36. return(b);
  37. else if (b == NULL)
  38. return(a);
  39. /* Pick either a or b, and recur */
  40. if (a->data <= b->data) {
  41. result = a;
  42. result->next = mergeTwoLists(a->next, b);
  43. }else {
  44. result = b;
  45. result->next = mergeTwoLists(a, b->next);
  46. }
  47. return(result);
  48. }
  49.  
  50. /* Driver program to test above functions*/
  51. int main(){
  52. /* Start with the empty list */
  53. listNode *a = NULL;
  54. listNode *b = NULL;
  55.  
  56. /* Let us create a unsorted linked lists to test the functions
  57.   Created lists shall be a: 2->3->20->5->10->15 */
  58. push(&a, 15);
  59. push(&a, 10);
  60. push(&a, 5);
  61.  
  62. push(&b, 20);
  63. push(&b, 3);
  64. push(&b, 2);
  65. push(&b, 1);
  66.  
  67. printList(a);
  68. printList(b);
  69. /* Sort the above created Linked List */
  70. listNode *result = mergeTwoLists(a, b);
  71. printf("Merged Linked List is: ");
  72. printList(result);
  73.  
  74. return 0;
  75. }
Success #stdin #stdout 0s 10320KB
stdin
Standard input is empty
stdout
5 10 15 
1 2 3 20 
Merged Linked List is: 1 2 3 5 10 15 20