首页 > 其他分享 >LeetCode 21 合并两个有序链表

LeetCode 21 合并两个有序链表

时间:2022-08-24 19:36:15浏览次数:52  
标签:ListNode 21 temp cur1 next 链表 val cur2 LeetCode

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        ListNode* cur1 = list1;
        ListNode* cur2 = list2;
        ListNode* temp = new ListNode(0);
        ListNode* res = temp;

        while (cur1 && cur2) {
            if (cur1 ->val <= cur2 ->val) {
                temp ->next = cur1;
                cur1 = cur1 ->next;
                
            }
            else {
                temp ->next = cur2;
                cur2 = cur2 ->next;
            }
            temp = temp ->next;
        }
        //扫尾
        while (cur1) temp ->next = cur1, temp = temp ->next, cur1 = cur1 ->next;
        while (cur2) temp ->next = cur2, temp= temp ->next, cur2 = cur2 ->next;

        return res ->next;
    }
};

标签:ListNode,21,temp,cur1,next,链表,val,cur2,LeetCode
From: https://www.cnblogs.com/hjy94wo/p/16621291.html

相关文章

  • P5021 [NOIP2018 提高组] 赛道修建 思路简记
    发现答案具有单调性,尝试一下二分答案能不能做二分答案\(t\)后,问题的关键就变成最多能找到多少条长度大于等于\(t\)的赛道我们先假设整棵树以\(1\)为根把样例的图......
  • 动态规划——leetcode55、跳跃游戏
    题目描述: 解题方法:动态规划动态规划解题步骤:确定状态:最后一步:如果能跳到最后一个下标,我们考虑他的最后一步到n-1(最后一个下标),这一步是从i跳过......
  • #前端算法救赎系列#LeetCode01.两数之和
    1.两数之和给定一个整数数组nums和一个整数目标值target,请你在该数组中找出和为目标值target的那两个整数,并返回它们的数组下标。示例1:输入:nums=[2,7,11,1......
  • LeetCode 142. 环形链表 II
    思路:快慢指针法:当快指针与慢指针相遇时,分别从起点,相遇点开始走,相遇即为环入口/***Definitionforsingly-linkedlist.*structListNode{*intval;*......
  • LeetCode 24. 两两交换链表中的节点
    /***Definitionforsingly-linkedlist.*structListNode{*intval;*ListNode*next;*ListNode():val(0),next(nullptr){}*List......
  • LeetCode 206. 反转链表
    /***Definitionforsingly-linkedlist.*structListNode{*intval;*ListNode*next;*ListNode():val(0),next(nullptr){}*ListN......
  • leetcode 热题100刷题-二叉树的中序遍历
    题题号:94题目:二叉树的中序遍历难度:简单链接:https://leetcode.cn/problems/binary-tree-inorder-traversal/2022/08/23答案算法思路  本题在课程中是学过的。  ......
  • [Oracle] LeetCode 696 Count Binary Substrings
    Givenabinarystrings,returnthenumberofnon-emptysubstringsthathavethesamenumberof0'sand1's,andallthe0'sandallthe1'sinthesesubstring......
  • IDEA2021.1.2版本使用Git解决代码冲突
    一、push时遇到冲突当前分支主管的推送被拒绝推送前需要合并远程更改   当前分支主管的推送被拒绝  推送前需要合并远程更改  当push时遇到冲突,要先pul......
  • IDEA2021.1.2版本使用Git
    IDEA中类的颜色红色:工作区已修改并未添加到暂存区绿色:修改已经添加到暂存区暂未提交到版本库黑色|白色:版本库与工作区一致nothingtocommit,workingtreeclea......