当前位置: 移动技术网 > IT编程>开发语言>C/C++ > #leetcode刷题之路21-合并两个有序链表

#leetcode刷题之路21-合并两个有序链表

2019年03月15日  | 移动技术网IT编程  | 我要评论

蔡贞安老公,抛光轮,韩信 季桃

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

 

思路:始终让l1是头节点小的那一个,然后拿l2的节点值依次与l1比较并插入l1中。最后返回l1。

#include <iostream>
using namespace std;
struct listnode {
        int val;
         listnode *next;
        listnode(int x) : val(x), next(null) {}
    };

listnode* createlist(int n)//有头节点的
{
    listnode *head = (listnode*)malloc(sizeof(listnode));
    listnode *pre = head;
    for (int i = 0; i < n; i++)
    {
        listnode *p = (listnode*)malloc(sizeof(listnode));
        cin >> p->val;
        pre->next = p;
        pre = p;
    }
    pre->next = nullptr;
    return head;
}

listnode* mergetwolists(listnode* l1, listnode* l2) {
    listnode*temp;
    listnode*t;
    if(l1== nullptr) return l2;
    if(l2== nullptr) return l1;
    if(l1->val>l2->val)//把头节点值小的放前面
    {
        t=l1;l1=l2;l2=t;
    }
    listnode*head=l1;
    while(l2!= nullptr)
    {
        if(l1->next== nullptr)
        {
            l1->next=l2;
            return head;
        }
        else if(l1->val<=l2->val&&l1->next->val>=l2->val)
        {
            temp=l2->next;
            t=l1->next;
            l1->next=l2;
            l2->next=t;
            l1=l2;
            l2=temp;
        }
        else l1=l1->next;
    }
    return head;
}
int main() {
    listnode* l1=createlist(3);
    listnode* l2=createlist(3);
    listnode *ans=mergetwolists(l1->next,l2->next);
    //ans=ans->next->next;
    while(ans!= nullptr)
    {
        cout<<ans->val<<endl;
        ans=ans->next;
    }
    return 0;
}

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网