fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. typedef struct Node {
  6. struct Node *next;
  7. int data;
  8. } Node;
  9.  
  10. void MoveNode(Node **dest, Node **source){
  11. Node *newNode = *source;
  12. *source = newNode->next;
  13. newNode->next = *dest;
  14. *dest = newNode;
  15. }
  16.  
  17. Node *MergedSort(Node *a, Node *b) {
  18. Node *head = NULL;
  19. Node **tail = &head;
  20. while(1) {
  21. if (a == NULL){
  22. *tail = b;
  23. break;
  24. } else if (b == NULL){
  25. *tail = a;
  26. break;
  27. } else if (a->data < b->data){
  28. MoveNode(tail, &a);
  29. } else{
  30. MoveNode(tail, &b);
  31. }
  32. tail = &((*tail)->next);
  33. }
  34. return head;
  35. }
  36.  
  37.  
  38. int main(void) {
  39. Node *a = malloc(sizeof(Node));
  40. a->data = 1;
  41. a->next = malloc(sizeof(Node));
  42. Node *t = a->next;
  43. t->data = 3;
  44. t->next = malloc(sizeof(Node));
  45. t = t->next;
  46. t->data = 5;
  47. t->next = NULL;
  48. Node *b = malloc(sizeof(Node));
  49. b->data = 2;
  50. b->next = malloc(sizeof(Node));
  51. t = b->next;
  52. t->data = 4;
  53. t->next = malloc(sizeof(Node));
  54. t = t->next;
  55. t->data = 6;
  56. t->next = NULL;
  57. Node *r = MergedSort(a, b);
  58. while (r) {
  59. printf("%d\n", r->data);
  60. r = r->next;
  61. }
  62. return 0;
  63. }
  64.  
Success #stdin #stdout 0s 2292KB
stdin
Standard input is empty
stdout
1
2
3
4
5
6