描述:
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
输入: {1,3,5},{2,4,6}
返回值: {1,2,3,4,5,6}
#include<stdio.h>
class Node{
public:
int val;
Node* next;
Node(int v):val(v),next(nullptr){};
~Node(){};
};
Node* combin(Node* root1,Node* root2){
if(root1 == nullptr){
return root2;
}
if(root2 == nullptr){
return root1;
}
Node* head = new Node(-1);
Node* cur = head;
while (root1 && root2)
{
if(root1->val < root2->val){
cur->next = root1;
root1 = root1->next;
}else{
cur->next = root2;
root2=root2->next;
}
cur = cur->next;
}
while (root1)
{
cur->next = root1;
root1 = root1->next;
cur = cur->next;
}
while (root2)
{
cur->next = root2;
root2 = root2->next;
cur= cur->next;
}
return head->next;
}
Node* buildList(int nums[],int len){
Node* head = new Node(nums[0]);
Node* cur = head;
if(len <=1){
return head;
}
for(int i =1;i<len;i++){
cur->next = new Node(nums[i]);
cur = cur->next;
}
cur->next = nullptr;
return head;
}
void showList(Node* head){
if(!head){
return;
}
while ((head))
{
printf("%d ",head->val);
head = head->next;
}
printf("\n");
}
int main(){
int nums1[5] = {1,3,5,7,9};
int nums2[5] = {2,4,6,8,10};
Node* head1 = buildList(nums1,5);
Node* head2 = buildList(nums2,5);
showList(head1);
showList(head2);
Node* head = combin(head1,head2);
showList(head);
return 0;
}