力扣21. 合并两个有序链表

题目

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

链接:21. 合并两个有序链表 - 力扣(LeetCode)

题解

设置两个指针head和tail,head用来指向新链表的头结点,tail用来进行新链表的尾插。比较两个链表,取较小的结点进行尾插。

注意,当有一个链表为空时,直接返回另一个非空链表;当有一个链表先为空时,tail直接指向非空链表,合并结束,返回head。

 代码如下:

struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) 
{
    struct ListNode* head = NULL;
    struct ListNode* tail = NULL;
    if (list1 == NULL)
        return list2;
    if (list2 == NULL)
        return list1;

    while (list1 && list2)
    {
        if (list1->val <= list2->val)
        {
            if (tail == NULL)
                head = tail = list1;
            else
            {
                tail->next = list1;
                tail = tail->next;
            }
            list1 = list1->next;
        }
        else
        {
            if (tail == NULL)
                head = tail = list2;
            else
            {
                tail->next = list2;
                tail = tail->next;
            }
            list2 = list2->next;
        }
    }
    if (list1)
        tail->next = list1;
    if (list2)
        tail->next = list2;
    return head;
}

猜你喜欢

转载自blog.csdn.net/minLi_/article/details/131726939