当前位置:网站首页>【剑指Offer】面试题25.合并两个有序的链表
【剑指Offer】面试题25.合并两个有序的链表
2022-06-13 04:16:00 【LuZhouShiLi】
面试题25.合并两个有序的链表
题目
输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
思路
- 设置dummy为一个空结点,作为新的链表,所以最后返回的就是dummy.next,设置cur为当前节点,从dummy开始
- 两个链表都是非空作为循环条件,每次选取两个链表中的较小节点,相应链表节点后移一位
- 每次循环之后cur也要后移一位,如果循环结束之后,链表非空,将cur指向非空链表
- 最后,返回dummy.next
代码
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode();// 定义一个哑节点
ListNode cur = dummy;
while(l1 != null && l2 != null)
{
// 每次选取较小的节点值
if(l1.val <= l2.val)
{
cur.next = l1;
l1 = l1.next;
}
else
{
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
// 如果有一个链表的节点没有被合并完毕,那么将该链表中的所有节点全部合并到新的链表中
if(l1 != null)
{
cur.next = l1;
}
if(l2 != null)
{
cur.next = l2;
}
return dummy.next;
}
}
边栏推荐
- Single chip microcomputer: basic concepts of a/d and d/a
- 1.4.2 Capital Market Theroy
- leetcode.1 --- 两数之和
- Dumi builds a document blog
- 缓存读写--写
- [test development] use case
- [MySQL] index and transaction
- How can a sweeping robot avoid obstacles without "mental retardation"? Analysis of five mainstream obstacle avoidance techniques
- EGO Planner代码解析----CMakeLists.txt和package.xml
- Introduction to MCU peripherals: temperature sensor DS18B20
猜你喜欢
环评图件制作-数据处理+图件制作
Ego planner code analysis ----cmakelists Txt and package xml
Solution to failure to download files by wechat scanning QR code
Single chip microcomputer: main index of a/d (analog-to-digital conversion)
Data analysis report
Reread the classic: end to end object detection with transformers
Use the visual studio code terminal to execute the command, and the prompt "because running scripts is prohibited on this system" will give an error
knife4j aggregation 2.0.9支持路由文档自动刷新
电磁兼容常用名词术语
No more! Another member of the team left..
随机推荐
Understand the pseudo static configuration to solve the 404 problem of refreshing the page of the deployment project
Dumi builds a document blog
leetcode.1 --- 两数之和
个人总结的MVP框架
El expression
On the value of line height
SCM signal generator program
Reread the classic: end to end object detection with transformers
Intervention analysis + pseudo regression
Lenovo notebook computer uses the insert key. When the mouse becomes a small square, how to solve it
【自动化测试】关于unittest你需要知道的事
Discussion sur la modélisation de la série 143
[笔记]vs2015 编写汇编masm32之使用MASM32库
基于PHP的轻量数码商城系统
Real time question answering of single chip microcomputer / embedded system
JSTL -- JSP standard tag library
【LeetCode】860. Change with lemonade (2 brushes for wrong questions)
MSG messages in ROS
[note]vs2015 compilation of masm32 using MASM32 Library
PAT 1054 The Dominant Color