Merge Two Sorted Lists

本文介绍了如何使用C++合并两个已排序的链表,并通过提供的代码实现。代码实例展示了如何遍历两个链表,比较节点值,并将较小的节点连接到新链表中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 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.


  • 这道题的解法跟上一篇博客中的揭发雷同,这个相当于重排一下单链表的指针,使两个有序的单链表合并以后还是有序的。C++代码如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
    ListNode *head = NULL, *curNode = NULL;

    if(!l1 && !l2)
        return NULL;
    else if(!l1)
        return l2;
    else if(!l2)
        return l1;

    while(l1 && l2)
    {
        if(l1->val > l2->val)
        {
            if(!head){
                head = l2;
                curNode = head;
            }
            else
            {
                curNode->next = l2;
                curNode = curNode->next;
            }
            l2 = l2->next;

        }
        else
        {
            if(!head){
                head = l1;
                curNode = head;
            }
            else
            {
                curNode->next = l1;
                curNode = curNode->next;
            }
            l1 = l1->next;
        }
    }

    ListNode *tempNode = l1 ? l1:l2;
    while(tempNode)
    {
        curNode->next = tempNode;
        tempNode = tempNode->next;
        curNode = curNode->next;
    }

    return head;
    }
};

  • 测试代码如下:
int main(int argc, const char * argv[])
{
    vector<int> numbers = vector<int>{-1, 0, 1, 2, -1, -4};

    ListNode *head = new ListNode(1);
    ListNode *mid = new ListNode(5);
    mid->next = NULL;
    head->next = mid;

    ListNode *last = new ListNode(8);
    last->next = NULL;
    mid->next = last;

    ListNode *head2 = new ListNode(4);

    ListNode *mid2 = new ListNode(6);
    mid2->next = NULL;
    head2->next = mid2;

    ListNode *last2 = new ListNode(9);
    last2->next = NULL;
    mid2->next = last2;


    cout<<"Show time!"<<endl;

    ListNode *ret = mergeTwoLists(head, head2);

    while(ret)
    {
        cout<<ret->val;
        ret = ret->next;
    }
    cout<<endl;


    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值