LeetCode 21 Merge Two Sorted Lists 把两个链表有序连接
2015-05-05 10:21
489 查看
题目:
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.
翻译:
把2个有序链表连接,返回一个新链表
思路:
很简单,就是遍历每个节点,小的话添加在新链表的后面。如果一个为空,则把另一个接在新链表结尾。
第二种思路就是以一个链表为基准,然后和另一个比较,如果l2的节点值小于这个,则把l2节点插入,然后l2向后移动一位。
代码1:
代码2:
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.
翻译:
把2个有序链表连接,返回一个新链表
思路:
很简单,就是遍历每个节点,小的话添加在新链表的后面。如果一个为空,则把另一个接在新链表结尾。
第二种思路就是以一个链表为基准,然后和另一个比较,如果l2的节点值小于这个,则把l2节点插入,然后l2向后移动一位。
代码1:
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode root = new ListNode(0); ListNode pre = root; pre.next = l1; while(l1!=null && l2!=null) { if(l1.val > l2.val)//@1 { ListNode next = l2.next; l2.next = pre.next; pre.next = l2; l2 = next; pre = pre.next; } else { l1 = l1.next; pre = pre.next; } } if(l1 == null) { pre.next = l2; } return root.next; }@1 处首先保存L2的下一个节点,然后把L2的这个节点插入到L1中,最后在把L2指向刚才保存的节点。
代码2:
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode root = new ListNode(0); ListNode pre = root; pre.next = l1; while(true) { if(l1 == null) { pre.next = l2; break; } if(l2 == null) { pre.next = l1; break; } if(l1.val < l2.val) { pre.next = l1; l1 = l1.next; } else { pre.next = l2; l2 = l2.next; } pre = pre.next; } return root.next; }代码2 比较简单易懂。就不多说明了。
相关文章推荐
- [LeetCode 21]Merge Two Sorted Lists 合并两个有序链表
- [LeetCode21]Merge Two Sorted Lists(合并两个有序链表)
- [LeetCode-21] Merge Two Sorted Lists(合并两个有序链表)
- 面试题17:合并两个有序链表(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:Merge Two Sorted Lists (链接两个有序链表)【面试算法题】
- [LeetCode]Merge Two Sorted Lists & Remove Duplicates from Sorted List 两个有序链表合并为一个&删除链表重复元素
- LeetCode-Merge Two Sorted Lists--链接两个有序链表
- Merge Two Sorted Lists 合并两个有序链表@LeetCode
- [LeetCode] 21. Merge Two Sorted Lists 合并有序链表
- LeetCode Merge Two Sorted Lists(合并两个有序链表)
- LeetCode(Merge Two Sorted Lists ) 合并两个有序的链表
- [LeetCode] Merge Two Sorted Lists 合并两个有序链表
- LeetCode--Merge Two Sorted Lists(合并两个有序链表)Python
- 【LeetCode刷题】排列两个有序链表Merge Two Sorted Lists(递归思想)(java)
- LeetCode-21- Merge Two Sorted Lists(合并两个已排序链表)
- leetcode Merge Two Sorted Lists 合并两个有序链表