21. Merge Two Sorted Lists

来源:互联网 发布:金山网络官网个人中心 编辑:程序博客网 时间:2024/05/19 19:57

题目:Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

多申请一个头结点,谁小,就把谁添加到头结点所在链表的后面。


代码:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {    struct ListNode* head=(struct ListNode*)malloc(sizeof(struct ListNode));    struct ListNode* pre=head;    while(l1 && l2)    {        if(l1->val <= l2->val)        {            pre->next=l1;            l1=l1->next;                    }        else        {            pre->next=l2;            l2=l2->next;                    }        pre=pre->next;    }    if(l1)pre->next=l1;    if(l2)pre->next=l2;        return head->next;}








0 0
原创粉丝点击