题解-合并有序链表

描述:
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
输入: {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;
}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容