Merge Two Sorted Lists
来源:互联网 发布:手机淘宝怎么设置心选 编辑:程序博客网 时间:2024/05/14 10:36
题目
Merge two sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should be made by splicing together the nodes of the two lists and sorted in ascending order.
将两个排序链表合并为一个新的排序链表算法
这一题和Merge Sorted Array差不多,用一个链表节点pre表示当前链表节点的上一个节点,我们用helper表示要求链表的虚头节点,我们将helper的下一个节点指向l1的第一个节点步骤如下
1 比较l1和l2值的大小,如果l1值大于l2值,将当前节点(pre.next)指向l2,之后再回来指向l1,此时l2移向下一节点;如果l1小于l2的值,应为目标一直指向的是l1,只把l1后移就行。
2 最后当l2还剩有值时,只把pre.next指向l2就行
public ListNode mergeTwoLists(ListNode l1, ListNode l2) { // write your code here ListNode helper = new ListNode(0); //虚节点 ListNode pre = helper; helper.next = l1; //结果指向l1 while (l1 != null && l2 != null) { if (l1.val > l2.val) { //当l2值大于l1值时 ListNode next = l2.next; // 保存l2的下节点1 l2.next = pre.next; //包村l1节点,pre.next指向l1 2 pre.next = l2; //将l2节点赋予当前节点 和2 一起又将下节点指向l1 l2 = next; //和1一起将l2挪下一节点 } else { l1 = l1.next; //目标一直指向l1节点,不用变换 } pre = pre.next; } if (l2 != null) { pre.next = l2; } return helper.next; }
0 0
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- hackinglab.cn注入关之三
- 第九周 项目4--广义表算法库及应用(2)
- LVS最简集群配置实战
- ucenter通信原理分析
- VS环境中某些工具栏上的控件不见了,例如 : 平台选项
- Merge Two Sorted Lists
- elasticsearch遇到的一点问题
- LeetCode 2016 167,382
- 判断一个分数是否为无限循环小数
- 分布式Session的几种实现方式
- 查找算法
- Android知识库
- 第一次分享
- mpi 程序打头