题目
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
分析
由于题目给出了两个链表是递增数组,那么直接同时遍历两个链表,判断结点值谁小,就接到新链表里,并将对应链表指针向前移,直至一个链表为空,训练环结束之后将不为空的链表直接加到新链表表尾即可。
github链接:JZ16-合并两个排序的链表
C++代码
#include <iostream>
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){
if(pHead1 == NULL){
return pHead2;
}
if(pHead2 == NULL){
return pHead1;
}
ListNode* head = new ListNode(0);
ListNode* tmp = head;
ListNode* node;
while(pHead1 && pHead2){
if(pHead1->val <= pHead2->val){
node = new ListNode(pHead1->val);
pHead1 = pHead1->next;
}else{
node = new ListNode(pHead2->val);
pHead2 = pHead2->next;
}
tmp->next = node;
tmp = tmp->next;
}
if(pHead1){
tmp->next = pHead1;
}
if(pHead2){
tmp->next = pHead2;
}
head = head->next;
return head;
}
};
int main(){
int n,m;
while(cin>>n>>m){
ListNode* head1 = new ListNode(0);
ListNode* head2 = new ListNode(0);
ListNode* tmp = head1;
int v;
for(int i = 0 ; i < n ; i++){
cin>>v;
ListNode* node = new ListNode(v);
head1->next = node;
head1 = head1->next;
}
head1 = tmp->next;
tmp = head2;
for(int i = 0 ; i < m ; i++){
cin>>v;
ListNode* node = new ListNode(v);
head2->next = node;
head2 = head2->next;
}
head2 = tmp->next;
tmp = head1;
while(tmp){
cout<<tmp->val<<" ";
tmp = tmp->next;
}
cout<<endl;
tmp = head2;
while(tmp){
cout<<tmp->val<<" ";
tmp = tmp->next;
}
cout<<endl;
Solution s;
tmp = s.Merge(head1,head2);
while(tmp){
cout<<tmp->val<<" ";
tmp = tmp->next;
}
}
return 0;
}