LeetCode-21 Merge Two Sorted Lists(合并两个有序链表)
来源:互联网 发布:exe mac要怎么打开 编辑:程序博客网 时间:2024/05/22 01:28
LeetCode-21 Merge Two Sorted Lists(合并两个有序链表)
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
代码:
public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) {ListNode flag = new ListNode(0);ListNode firstflag = flag;//标记第一个节点位置。while (l1 != null && l2 != null) {//★if(l1.val < l2.val){flag.next = l1;l1 = l1.next;}else {flag.next = l2;l2 = l2.next;}flag = flag.next;}flag.next = l1 != null ? l1 : l2; return firstflag.next; }}
事实上我认为在★的循环体内部能够进行优化。
在该处再加入while循环,判断L2新节点和l1当前节点的大小,如果依旧比l1当前节点大,则l2=l2.next~直到出现比当前节点大的节点,就将L2的上一个节点与l1连接,并l1的下一个节点继续判断...(重复刚刚l2的推进过程)...,这样可以减少连接次数。
0 0
- Merge Two Sorted Lists 合并两个有序链表@LeetCode
- [LeetCode]Merge Two Sorted Lists-合并两个有序链表
- Leetcode Merge Two Sorted Lists 合并两个有序链表
- leetcode Merge Two Sorted Lists 合并两个有序链表
- Leetcode Merge Two Sorted Lists(合并两个有序表)
- LeetCode-21 Merge Two Sorted Lists(合并两个有序链表)
- [LeetCode-21] Merge Two Sorted Lists(合并两个有序链表)
- 两个有序链表的合并 Merge Two Sorted Lists
- Merge Two Sorted Lists 合并两个有序链表
- Merge Two Sorted Lists, 合并两个有序链表
- Merge Two Sorted Lists(合并两个有序链表)
- LeetCode(Merge Two Sorted Lists ) 合并两个有序的链表
- LeetCode OJ 之 Merge Two Sorted Lists(合并两个有序的链表)
- LeetCode Merge Two Sorted Lists(合并两个有序链表)
- LeetCode--Merge Two Sorted Lists(合并两个有序链表)Python
- Leetcode:Merge Two Sorted Lists 合并两个有序单链表
- (LeetCode)Merge Two Sorted Lists --- 合并两个有序序列
- LeetCode-Merge Two Sorted Lists--链接两个有序链表
- 中英文字体对照表
- 3.结构体与链表
- 在ARM linux上使用usb接口的触屏
- 第一个struct
- [C++]KMP算法实现
- LeetCode-21 Merge Two Sorted Lists(合并两个有序链表)
- 树形DP进阶之背包问题
- 第八章 List Dictionaries
- C#设计模式(单例
- windows下安装MongoDB
- iOS UITextField 限制用户输入小数点后位数的方法
- C,C++宏中#与##的讲解
- Android侧滑SliddingMenu+Activity详解
- 蓝桥杯---蚂蚁感冒(水题)