归并两个有序链表

struct ListNode{
int val;
ListNode* next;
ListNode(int x) :val(x), next(NULL){}

};


ListNode* mergeList(ListNode* left, ListNode* right)
{
ListNode* head = NULL;
ListNode* p = NULL;
while (left && right){
if (head == NULL){
if (left->val <= right->val){
head = left;
left = left->next;
}
else{
head = right;
right = right->next;
}
p = head;
}
else{
if (left->val <= right->val){
p->next = left;
left = left->next;
}
else{
p->next = right;
right = right->next;
}
p = p->next;
}
}
if (left){
p->next = left;
}
if (right){
p->next = right;
}
return head;
}

你可能感兴趣的:(C++,归并排序)