当前位置:网站首页>剑指 Offer 25. 合并两个排序的链表
剑指 Offer 25. 合并两个排序的链表
2022-07-26 11:05:00 【孙中明】
/** * 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) {
//设置两个指针,分别指向l1和l2,然后对齐进行遍历
//然后插入res 返回res
// 归并
ListNode res = new ListNode(-1);
ListNode pre=res;
while(l1!=null && l2!=null){
if(l1.val<=l2.val){
pre.next=l1;
pre=pre.next;
l1=l1.next;
}else{
pre.next=l2;
pre=pre.next;
l2=l2.next;
}
}
if(l1!=null){
pre.next=l1;
}
if(l2!=null){
pre.next=l2;
}
return res.next;
}
}

边栏推荐
猜你喜欢
随机推荐
贝尔曼期望方程状严谨证明
雨课堂 《知识产权法》笔记
easyui01
像素和内存的关系
Basic concepts of JVM and memory management model
MySQL事务详解
1837. Sum of digits under k-ary representation
Leetcode-209. subarray with the smallest length (binary, prefix and, sliding window)
MySQL basic knowledge summary
Access rights - private, public, protected
Postman export import
Bash shell learning notes (III)
AuthorizingRealm简介说明
MySQL locking mechanism
由浅入深搭建神经网络
[development tool] ieda red
Three properties of concurrency
easyui04
Why give up NPM and turn to yarn
Linkedblockingqueue of novice source code




![[idea]如何新建一个项目](/img/33/f210d59ccd3664487f401929dac24c.png)




