您的位置:首页 > 其它

【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 算法