Merge two sort list

#include
#include<vector>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}

};
ListNode* mergeTwoList(ListNode* l1, ListNode* l2)
{
ListNode * temp = new ListNode(0);


if (l1 == NULL && l2 == NULL)
return NULL;
if (l1 == NULL)
return l2;
if (l2 == NULL)
return l1;
if (l1->val > l2->val)
{
temp = l1;
l1 = l2;
l2 = temp;
}
ListNode * res = l1;


while (l1 != NULL && l2 != NULL)
{
if(l1->val <= l2->val)
{

if (l1->next != NULL && l1->next->val > l2->val)
{
ListNode * temp1 = new ListNode(0);   ////一定要新建結點!!!
temp1->val = l2->val;
temp1->next = l1->next;
l1->next = temp1;
l2 = l2->next;
l1 = temp1;        //l1 = temp1->next .... (X)  因爲如果l2中多個數字均介於l1當前數字與下一個數字之間的話,會出現問題。如:l1: ...-3,7,....    l2:  ...0,1,2,3,...
}
else if (l1->next != NULL)
{
l1 = l1->next;
}
else
break;
}

}
if (l2 != NULL)
l1->next = l2;
return res;
}
int main()
{
ListNode * head1 = new ListNode(-10);
ListNode * head2 = new ListNode(-5);
ListNode* head11 = head1;
ListNode* head22 = head2;
ListNode* res = new ListNode(0);
int a = 0,b = 0;
for (int i = 1; i < 6; i++)
{
cin >> a >> b;


ListNode*l1 = new ListNode(a);
ListNode*l2 = new ListNode(b);
head1->next = l1;
head1 = l1;
head2->next = l2;
head2 = l2;
}
ListNode* l3 = new ListNode(9);
head1->next = l3;
ListNode*head11_show =head11;
ListNode*head22_show = head22;
while (head11_show != NULL)
{
cout << head11_show->val << "  ";
head11_show = head11_show->next;
}
while (head22_show != NULL)
{
cout << head22_show->val << "  ";
head22_show = head22_show->next;
}
res = mergeTwoList(head11,head22);
while (res != NULL)
{
cout << res->val << "  ";
res = res->next;
}

system("pause");
return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章