劍指offer 題解 | #合并兩個排序的鏈表#
合并兩個排序的鏈表
http://fangfengwang8.cn/practice/d8b6b4358f774294a89de2a6ac4d9337
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代碼中的類名、方法名、參數(shù)名已經(jīng)指定,請勿修改,直接返回方法規(guī)定的值即可 * * * @param pHead1 ListNode類 * @param pHead2 ListNode類 * @return ListNode類 */ public ListNode Merge (ListNode pHead1, ListNode pHead2) { // write code here ListNode head = new ListNode(0); ListNode cur = head; ListNode p = pHead1; ListNode q = pHead2; while(p!=null && q!=null){ if(p.val < q.val){ cur.next = p; cur = p; p = p.next; }else{ cur.next = q; cur = q; q = q.next; } } // 是否有未完成的 if(p!=null){ cur.next = p; } if(q!=null){ cur.next = q; } return head.next; } }#曬一曬我的offer##劍指offer#