Merge Two Sorted Lists（easy）

114人阅读 评论(0)

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.

链接两个有序表即对两个有序列表进行合并

/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

while(l1!=null||l2!=null){
if(l1!=null&&l2!=null){
if(l1.val < l2.val){
p.next = l1;
l1=l1.next;
}else{
p.next=l2;
l2=l2.next;
}
p = p.next;
}else if(l1==null){
p.next = l2;
break;
}else if(l2==null){
p.next = l1;
break;
}
}

}

<pre class="hljs cs"><code><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> {
<span class="hljs-function"><span class="hljs-keyword">public</span> ListNode <span class="hljs-title">mergeTwoLists</span><span class="hljs-params">(ListNode l1, ListNode l2)</span> </span>{
ListNode head = <span class="hljs-keyword">new</span> ListNode(<span class="hljs-number">0</span>);
<span class="hljs-comment">// 依次比较拼接</span>
<span class="hljs-keyword">while</span>(l1 != <span class="hljs-keyword">null</span> && l2 != <span class="hljs-keyword">null</span>){
<span class="hljs-keyword">if</span>(l1.val <= l2.val){
curr.next = l1;
l1 = l1.next;
} <span class="hljs-keyword">else</span> {
curr.next = l2;
l2 = l2.next;
}
curr = curr.next;
}
<span class="hljs-comment">// 把剩余的全拼上去</span>
<span class="hljs-keyword">if</span>(l1 == <span class="hljs-keyword">null</span>){
curr.next = l2;
} <span class="hljs-function"><span class="hljs-keyword">else</span> <span class="hljs-title">if</span> <span class="hljs-params">(l2 == <span class="hljs-keyword">null</span>)</span></span>{
curr.next = l1;
}
}
}</code>

个人资料
等级：
访问量： 2万+
积分： 960
排名： 5万+