题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
解题思路:
参考答案:
#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <algorithm>
#include <math.h>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
};
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if (pHead1 == NULL && pHead2 == NULL)
return NULL;
if(pHead1 == NULL && pHead2 != NULL)
return pHead2;
if (pHead1 != NULL && pHead2 == NULL)
return pHead1;
ListNode* temp = new ListNode;
ListNode* move_head = temp;
ListNode* temp_head1 = pHead1;
ListNode* temp_head2 = pHead2;
while (temp_head1 != NULL && temp_head2 != NULL)
{
if (temp_head1->val < temp_head2->val)
{
move_head->next = temp_head1;
move_head = move_head->next;
temp_head1 = temp_head1->next;
} else if (temp_head1->val >= temp_head2->val)
{
move_head->next = temp_head2;
move_head = move_head->next;
temp_head2 = temp_head2->next;
}
}
if (temp_head1 == NULL)
{
move_head->next = temp_head2;
} else if (temp_head2 == NULL)
{
move_head->next = temp_head1;
}
return temp->next;
}
};
int main()
{
//创建链表
vector<int > array_list;
Solution solution;
//初始化链表内的参数
ListNode ListNode7 = {7,NULL};
ListNode ListNode6 = {6,&ListNode7};
ListNode ListNode5 = {5,&ListNode6};
ListNode ListNode4 = {4,&ListNode5};
ListNode ListNode3 = {3,&ListNode4};
ListNode ListNode2 = {2,&ListNode3};
ListNode ListNode1 = {1,&ListNode2};
ListNode ListNode13 = {11,NULL};
ListNode ListNode12 = {10,&ListNode13};
ListNode ListNode11 = {9,&ListNode12};
ListNode ListNode10 = {7,&ListNode11};
ListNode ListNode9 = {6,&ListNode10};
ListNode ListNode8 = {2,&ListNode9};
//将头指针指向第一个链表的地址
ListNode *head1 = &ListNode1;
ListNode *head2 = &ListNode8;
ListNode * my_result;
my_result = solution.Merge(head1,head2);
while (my_result)
{
cout<<"result:"<<my_result->val<<endl;
my_result = my_result->next;
}
return 0;
}