降序链表合并

题目:将两个降序链表合并为一个新的 降序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
如:{6,5,1}{8,5,2} 合并后:{8,6,5,5,2,1}

ListNode* MergeTwoLists(ListNode* list1, ListNode* list2)
{
    // write code here
    ListNode* node = new ListNode(-1);
    ListNode* node_0 = node;//备份头

    while (list1 ||  list2)
    {

        if (NULL == list1)
        {
            node->next = list2;
            return node_0->next;
        }

        if (NULL == list2)
        {
            node->next = list1;
            return  node_0->next;
        }

        if (list1->val >= list2->val)
        {
            node->next = list1;
            list1 = list1->next;
            node = node->next;
            node->next = NULL;//此处注意。先移List1后,再node->next = NULL;否则会把list1 设置NULL

        }
        else
        {
            node->next = list2;
            list2 = list2->next;
            node = node->next;
            node->next = NULL;
        }
    }
/*  考虑内存泄漏
    node = node_0;
    node_0 = node_0->next;
    delete node;
    return node_0;
*/
    return node_0->next;
}

此题考察的单链表操作。返回值还必须是链表头。验证下

int main()
{
    ListNode* node_1 = new  ListNode(6);
    ListNode* node_2 = new  ListNode(5);
    ListNode* node_3 = new  ListNode(1);
    node_1->next = node_2;
    node_2->next = node_3;
    
    ListNode* node_4 = new  ListNode(8);
    ListNode* node_5 = new  ListNode(5);
    ListNode* node_6 = new  ListNode(2);
    node_4->next = node_5;
    node_5->next = node_6;

    ListNode* a_list =  MergeTwoLists(node_1,node_4);
    while (a_list)
    {
        cout << a_list->val<<" ";
        a_list = a_list->next;
    }
    cout << endl;
    return 0;
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值