// Merge.cpp : Defines the entry point for the console application.
// NOTE: Altered MoveNode and SortedMerge function source is from http://cslibrary.stanford.edu/105/LinkedListProblems.pdf

#include
"stdafx.h"
struct
node
{
   
int data;
    node* next;
};

 

int Add(node& head, int value) {
    node* n = &head;
   
while(n) {
       
if(!n->next)
        {
            n->next =
new node;
            n->next->next = NULL;
            n->next->data = value;
           
return 1;
        }
   n = n->next;
  }
    
return 0;
}
 

void
MoveNode(struct node** destRef, struct node** sourceRef) {
    struct node* newNode = *sourceRef;

    *sourceRef = newNode->next;
    newNode->next = *destRef;
    *destRef = newNode;
}


struct
node* SortedMerge(struct node* a, struct node* b) {
    struct node dummy;
   
struct node* tail = &dummy;

    dummy.next = NULL;
   
while (1) {
       
if (a == NULL) {
            tail->next = b;
           
break;
        }
       
else if (b == NULL) {
            tail->next = a;
           
break;
        }

       
if(a->data == tail->data) a = a->next;
       
if(b->data == tail->data) b = b->next;

       
if (a->data < b->data) {
            MoveNode(&(tail->next), &a);
        }
       
else {
            MoveNode(&(tail->next), &b);
        }

        tail = tail->next;
    }
   
return(dummy.next);
}

int
_tmain(int argc, _TCHAR* argv[]) {
    node* head1 =
new node;
    head1->data = 0;
    head1->next = NULL;
    Add(*head1, 1);
    Add(*head1, 3);
    Add(*head1, 6);

    node* head2 =
new node;
    head2->data = 1;
    head2->next = NULL;
    Add(*head2, 2);
    Add(*head2, 3);
    Add(*head2, 4);
    Add(*head2, 5);

    node* list = SortedMerge(head1, head2);
    node* current = list;
   
while(current) {
        printf(
"%d \n", current->data);
        current = current->next;
    }
   
return 0;
}