您的位置:首页 > 编程语言 > C#

Leetcode 21. Merge Two Sorted Lists

2016-10-13 10:16 507 查看
原题链接:https://leetcode.com/problems/merge-two-sorted-lists/



思路:

0  处理边界条件
1  两个输入链表可能为空,采用dummy节点,使得dummy.next指向新链表的第一个节点。
2  初始化时,使用两个指针指向两个链表的表头,两个指针同时不为空时,取较小的节点放入新链表的尾部。
3  然后把链表中不为空的部分重新放到新链表的尾部。

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
//判断边界条件
if(l1==null && l2!=null)
return l2;
if(l1!=null && l2==null)
return l1;
if(l1==null && l2==null)
return null;
//创建头结点
ListNode head = new ListNode(0);
ListNode current = head;

while(l1!=null && l2!=null){
if(l1.val<=l2.val){//取较小值的节点
current.next = l1;
current = current.next;
l1 = l1.next;
}else{
current.next = l2;
current = current.next;
l2 = l2.next;
}
}
//将剩下的部分放置在合并后链表的尾部
if(l1!=null)
current.next= l1;
if(l2!=null)
current.next=l2;
return head.next;
}
}


什么情况下,我们需要使用dummy node?
http://blog.yangliu.online/2016/07/15/when-do-we-need-dummy-head-for-linked-list/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 LeetCode c#