当前位置:网站首页>合并两个有序链表(迭代)
合并两个有序链表(迭代)
2022-04-22 08:17:00 【学海无涯苦作舟呀】
题目链接:https://leetcode-cn.com/problems/merge-two-sorted-lists/
题目:将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
代码如下:
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode p = new ListNode(-1);
ListNode head = p;
while(l1!=null && l2!=null) {
if(l1.val<=l2.val) {
//如果l1的值小于等于l2的值
p.next=l1;//将p.next指向l1
l1=l1.next;//然后l1继续往后移动一位
} else {
/同理
p.next=l2;
l2=l2.next;
}
p=p.next;
}
//如果l1和l2不一样长,等遍历完后,将p的next指向没遍历完的链表即可
//也保证了l1或l2其中一个为空时,p.next指向另一个非空的链表。
p.next = (l1==null? l2:l1);
return head.next;//合并后的链表的第一个元素的入口
}
}
版权声明
本文为[学海无涯苦作舟呀]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_46184836/article/details/124270283
边栏推荐
- 【微信小程序】为小程序设置底部菜单(tabBar)
- Tissu hyperledger 1. 4 construction de l'environnement et essais d'échantillons
- How to view port occupied in window
- First knowledge of C language ~ circular statement
- RedHat7配置yum
- 机器学习之逻辑回归的步骤原理
- A growing tree
- goto Statement
- How can flume solve the problem of too many small files when collecting
- C语言的学习目标和大致内容
猜你喜欢

学习RHCSA的第三天

Tissu hyperledger 1. 4 construction de l'environnement et essais d'échantillons

Android Development - SQLite and sqlitedatabase Application Experiment 6 notes
![C language to realize [shutdown program]](/img/b3/0364fda1bc27d754dd11eec055979d.jpg)
C language to realize [shutdown program]

初识C语言~循环语句

How does CSDN reprint other people's blogs

Restore MySQL service after computer reset

C语言如何设置随机数

How to empty the input buffer

工业缺陷检测项目实战(四)——基于HRNet的陶瓷缺陷检测
随机推荐
悬空else问题
RHEL7——进程管理
Scanf / sprintf, fscanf / fprintf, sscanf / sprintf, snprintf of C language
CSDN如何转载文章
工业缺陷检测项目实战(二)——基于深度学习框架yolov5的钢铁表面缺陷检测
PCIe learning - how to make PCIe bus compatible with PCI bus in software (7)
The server is set to start automatically and regularly
插入排序及优化
Binary search [detailed explanation]
MyCms 自媒体 CMS 系统 v3.2.2,广告插件优化
一文2500字带你了解性能测试的那些基础知识
Advanced usage skills of nmap
TypeScript(1)
N states of prime number solution
机器学习之分类回归树
【微信小程序】为小程序设置底部菜单(tabBar)
学习RHCSA的第二天
Introduction to Nessus vulnerability scanning
==与equals
DTV terminology