【LeetCode】21. Merge Two Sorted Lists
2017-08-24 22:30
465 查看
题目描述:
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.合并两个已排序的链表,并返回一个新链表。新链表应该通过将前两个链表的节点拼接在一起来完成
此题考察的是数据结构里的链表,合并两个有序链表,可参考C语言实现两个有序链表的合并:http://blog.csdn.net/ontheroad_/article/details/72887097
值得注意的是要找出L1和L2中最小的结点,作为新链表的表头结点
/** * 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) { if(l1 == null){ return l2; } if(l2 == null){ return l1; } if(l1 == null && l2 == null){ return null; } ListNode p1 = l1; ListNode p2 = l2; ListNode head = null; if(p1.val < p2.val){ head = p1; p1 = p1.next; }else{ head = p2; p2 = p2.next; } ListNode p = head; while(p1 != null && p2 != null){ if(p1.val < p2.val){ p.next = p1; p = p.next; p1 = p1.next; }else{ p.next = p2; p = p.next; p2 = p2.next; } } if(p1 != null){ p.next = p1; } if(p2 != null){ p.next = p2; } return head; } }
相关文章推荐
- LeetCode 21 Merge Two Sorted Lists(合并链表)
- 【LeetCode 21】Merge Two Sorted Lists(Python)
- 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(合并两个有序单链表)
- 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(C++版)
- leetcode 21. Merge Two Sorted Lists(C语言,合并两个排序的链表为一个排序链表)32
- Leetcode 21 Merge Two Sorted Lists
- leetcode 21. Merge Two Sorted Lists
- leetcode-21-Merge Two Sorted Lists