您的位置:首页 > 其它

LeetCode OJ--Merge Two Sorted Lists

2014-01-18 10:26 330 查看
http://oj.leetcode.com/problems/merge-two-sorted-lists/

有序链表的归并排序

#include <iostream>
using namespace std;

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

class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
// default as asend sorted,merge sort
ListNode *ans = NULL,*ansEnd = NULL,*n1 = l1,*n2 = l2;
bool firstone = 1;
while(n1&&n2)
{
while(n1->val <= n2 ->val)
{
if(firstone == 1)
{
ans = ansEnd = n1;
//ansEnd = ans->next;
firstone = 0;
n1 = n1->next;
}
else
{
ansEnd->next = n1;
ansEnd = n1;
n1 = n1->next;
}
if(n1 == NULL)
break;
}
if(n1 == NULL)
break;
while(n1->val > n2->val)
{
if(firstone == 1)
{
ans = ansEnd = n2;
firstone = 0;
n2 = n2->next;
}
else
{
ansEnd->next = n2;
ansEnd = n2;
n2 = n2->next;
}
if(n2 == NULL)
break;
}
}
if(n1==NULL && n2!= NULL)
{
if(firstone ==1)
{
ans = n2;
return ans;
}
ansEnd->next = n2;
}
else if(n2 == NULL && n1 != NULL)
{
if(firstone == 1)
{
ans = n1;
return ans;
}
ansEnd->next = n1;
}
return ans;
}
};

int main()
{
ListNode *n1 = new ListNode(1);
ListNode *n2 = new ListNode(3);
ListNode *n3 = new ListNode(5);

n1->next = n2;

Solution myS;
ListNode *ans = myS.mergeTwoLists(NULL,NULL);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: