输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

// test14.cpp : 定义控制台应用程序的入口点。
//

include "stdafx.h"

include

include

include

include

include

include

include <initializer_list>

include

include

using namespace std;

struct ListNode {
int val;
struct ListNode next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
ListNode
Merge(ListNode* pHead1, ListNode* pHead2)
{
ListNode *newHead = pHead1, *temp;
vectorvec;
if (pHead1 == NULL)
return pHead2;
if (pHead2 == NULL)
return pHead1;

while (pHead1->next!=NULL)
{
pHead1 = pHead1->next;
}

pHead1->next = pHead2;
temp = newHead;

while (newHead!=NULL)
{
vec.push_back(newHead->val);
newHead = newHead->next;
}

newHead = temp;
sort(vec.begin(),vec.end());

for (auto it = vec.begin(); it != vec.end(); it++)
{
temp->val = *it;
temp = temp->next;
}

return newHead;

}
};

int main()
{
vector vec;
Solution so;

ListNode first(1);
ListNode second(4);
ListNode third(5);
ListNode four(6);
ListNode *head=&first;
first.next = &second;
second.next = &third;
third.next = &four;

ListNode first1(1);
ListNode second1(2);
ListNode third1(3);
ListNode four1(7);
ListNode *head1 = &first1;
first1.next = &second1;
second1.next = &third1;
third1.next = &four1;

ListNode result = so.Merge(head, head1);
while (result !=NULL)
{
cout << (
result).val<<" ";
result = (*result).next;
}

cout << endl;

return 0;
}

posted @ 2016-10-14 13:32  wdan2016  阅读(1042)  评论(0)    收藏  举报