Leetcode 21. Merge Two Sorted Lists
来源:互联网 发布:酒店水牌通过网络发送 编辑:程序博客网 时间:2024/05/20 06:09
题目来源:leetcode
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.
思路:以两个链表的头结点进行比较,找出较小的一个,从他开始分别比较两个链表的相应元素,将较小的出入到链表。知道有一个链表插入完成。将领一个未完成的插进来
由于表头元素比较叫麻烦(插入时候需要比较大小,输出的时候也需要确定从哪个链表开始的),所以虚拟一个表头
/** * 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 p=new ListNode(0); ListNode first=p; while(l1!=null&&l2!=null){ if(l1.val<l2.val){ first.next=l1; //first=first.next; l1=l1.next; } else{ first.next=l2; l2=l2.next; } first=first.next; } if(l1!=null){ first.next=l1; } if(l2!=null) first.next=l2; return p.next; } }
阅读全文
0 0
- 21. Merge Two Sorted Lists leetcode(lists)
- [LeetCode]21.Merge Two Sorted Lists
- LeetCode --- 21. Merge Two Sorted Lists
- LeetCode 21.Merge Two Sorted Lists
- [Leetcode] 21. Merge Two Sorted Lists
- 【LeetCode】21.Merge Two Sorted Lists
- 【leetcode】21. Merge Two Sorted Lists
- [leetcode] 21.Merge Two Sorted Lists
- [leetcode] 21.Merge Two Sorted Lists
- [leetcode] 21. Merge Two Sorted Lists
- <LeetCode OJ> 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists LeetCode
- leetcode 21. Merge Two Sorted Lists
- Leetcode:21. Merge Two Sorted Lists(JAVA)
- Leetcode ☞ 21. Merge Two Sorted Lists
- LeetCode 21. Merge Two Sorted Lists
- [LeetCode]21. Merge Two Sorted Lists
- 【LeetCode】21. Merge Two Sorted Lists
- JavaEE关于全局参数的
- python爬取百度音乐(二)——保存数据到mysql中
- JS Date函数整理
- 剑指offer 面试题63 二叉搜索树的第 k 个结点
- JavaScript中的==和===
- Leetcode 21. Merge Two Sorted Lists
- 方格分割
- 虚拟币开发专题(山寨币怎样通过挖矿最后把储存的币出完)
- python入门(三十):类的成员
- 【机器学习实战 第九章】树回归 CART算法的原理与实现
- JS实现复制功能,兼容各大主流浏览器复制神器 ZeroClipboard
- 使用序列化和反序列化实现深拷贝
- 关于《 MATLAB神经网络30个案例分析》坑的控诉
- js实现内容模块展开和收缩