题解 | #合并两个排序的链表#
合并两个排序的链表
http://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
using System.Collections.Generic;
/*
public class ListNode
{
public int val;
public ListNode next;
public ListNode (int x)
{
val = x;
}
}*/
class Solution
{
public ListNode Merge(ListNode pHead1, ListNode pHead2)
{
// write code here
if (pHead1 == null){
return pHead2;
}else if (pHead2 == null){
return pHead1;
}else{
ListNode pHeadNew = new ListNode(0);
ListNode tmp = pHeadNew;
while (pHead1!=null && pHead2!=null){
if (pHead1.val < pHead2.val){
tmp.next = pHead1;
pHead1 = pHead1.next;
tmp = tmp.next;
}else{
tmp.next = pHead2;
pHead2 = pHead2.next;
tmp = tmp.next;
}
}
tmp.next = (pHead1!=null)? pHead1 : pHead2;
return pHeadNew.next;
}
}
}
/*
public class ListNode
{
public int val;
public ListNode next;
public ListNode (int x)
{
val = x;
}
}*/
class Solution
{
public ListNode Merge(ListNode pHead1, ListNode pHead2)
{
// write code here
if (pHead1 == null){
return pHead2;
}else if (pHead2 == null){
return pHead1;
}else{
ListNode pHeadNew = new ListNode(0);
ListNode tmp = pHeadNew;
while (pHead1!=null && pHead2!=null){
if (pHead1.val < pHead2.val){
tmp.next = pHead1;
pHead1 = pHead1.next;
tmp = tmp.next;
}else{
tmp.next = pHead2;
pHead2 = pHead2.next;
tmp = tmp.next;
}
}
tmp.next = (pHead1!=null)? pHead1 : pHead2;
return pHeadNew.next;
}
}
}