zoukankan      html  css  js  c++  java
  • [Leetcode] 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.

    题意:合并两个排好的链表并返回新的链表。

    可以使用归并排序,从两链表的表头,取出结点,比较两值,将较小的放在新链表中。如1->3->5->6和2->4->7->8,先将1放入新链表,然后将3和2比较,较小值放入新链表中,从1到3只要pre=pre->next即可。当其中有一条链表被访问完,结束循环,找出该链表,将其接在新链表的后面即可。

    /**
     * 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 *newList=new ListNode(-1);
            ListNode *pre=newList;
            while(l1&&l2)
            {
                if(l1->val > l2->val)
                {
                    pre->next=l2;
                    l2=l2->next;
                }
                else
                {
                    pre->next=l1;
                    l1=l1->next;
                }
                pre=pre->next;
            }
            if(l1)
                pre->next=l1;
            else
                pre->next=l2;
    
            return newList->next;    
        }
    };
  • 相关阅读:
    Comet OJ
    AtCoder Grand Contest 002题解
    AtCoder Grand Contest 001 题解
    线性基求交
    2019牛客暑期多校训练营(第四场)题解
    AtCoder Grand Contest 036题解
    计算几何 val.2
    计算几何 val.1
    模拟退火学习笔记
    动态点分治学习笔记
  • 原文地址:https://www.cnblogs.com/love-yh/p/7007117.html
Copyright © 2011-2022 走看看