Merge two sorted lists
/*
Merge two sorted lists A and B as one linked list
Node is defined as
struct Node
{
int data;
struct Node *next;
}
*/
Node* MergeLists(Node *headA, Node* headB)
{
// This is a "method-only" submission.
// You only need to complete this method
Node *tmpA = headA, *tmpB = headB, *headC, *tmpC, x;
headC = &x;
headC -> next = NULL;
tmpC = headC;
while(tmpA != NULL && tmpB != NULL)
{
if(tmpA -> data <= tmpB -> data )
{
Node *t = tmpA;
tmpA = tmpA -> next;
tmpC -> next = t;
t -> next = NULL;
}
else
{
Node *t = tmpB;
tmpB = tmpB -> next;
tmpC -> next = t;
t -> next = NULL;
}
tmpC = tmpC -> next;
}
if(tmpA == NULL)
tmpC -> next = tmpB;
if(tmpB == NULL)
tmpC -> next = tmpA;
return headC -> next;
}
/*
Merge two sorted lists A and B as one linked list
Node is defined as
struct Node
{
int data;
struct Node *next;
}
*/
Node* MergeLists(Node *headA, Node* headB)
{
// This is a "method-only" submission.
// You only need to complete this method
Node *tmpA = headA, *tmpB = headB, *headC, *tmpC, x;
headC = &x;
headC -> next = NULL;
tmpC = headC;
while(tmpA != NULL && tmpB != NULL)
{
if(tmpA -> data <= tmpB -> data )
{
Node *t = tmpA;
tmpA = tmpA -> next;
tmpC -> next = t;
t -> next = NULL;
}
else
{
Node *t = tmpB;
tmpB = tmpB -> next;
tmpC -> next = t;
t -> next = NULL;
}
tmpC = tmpC -> next;
}
if(tmpA == NULL)
tmpC -> next = tmpB;
if(tmpB == NULL)
tmpC -> next = tmpA;
return headC -> next;
}
No comments:
Post a Comment