LeetCode 热题100 21. 合并两个有序链表
2022/6/24 23:20:15
本文主要是介绍LeetCode 热题100 21. 合并两个有序链表,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
题目:
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
解析:
采用双指针,分别指向两个链表,然后将两个链表较小的那个添加到新链表中
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode() {} 7 * ListNode(int val) { this.val = val; } 8 * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 * } 10 */ 11 class Solution { 12 public ListNode mergeTwoLists(ListNode list1, ListNode list2) { 13 ListNode head = new ListNode(0); 14 ListNode tmp = new ListNode(); 15 tmp = head; 16 while(list1!=null && list2!=null){ 17 ListNode temp = new ListNode(); 18 if(list1.val<=list2.val){ 19 tmp.next=list1; 20 tmp=tmp.next; 21 list1=list1.next; 22 } 23 else{ 24 tmp.next=list2; 25 tmp=tmp.next; 26 list2=list2.next; 27 } 28 tmp.next=null; 29 } 30 while(list1 == null && list2!=null){ 31 tmp.next=list2; 32 tmp=tmp.next; 33 list2=list2.next; 34 tmp.next=null; 35 } 36 while(list2 == null && list1!=null){ 37 tmp.next=list1; 38 tmp=tmp.next; 39 list1=list1.next; 40 tmp.next=null; 41 } 42 return head.next; 43 } 44 }
,直到两个链表都为空。
代码:
这篇关于LeetCode 热题100 21. 合并两个有序链表的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升