1. 程式人生 > >0009 合並兩個有序鏈表

0009 合並兩個有序鏈表

linked 一個 emp listnode sts tro span next temp

將兩個有序鏈表合並為一個新的有序鏈表並返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。

示例:

輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
public class
Solution { public ListNode MergeTwoLists(ListNode l1, ListNode l2) { ListNode p1 = l1; ListNode p2 = l2; ListNode res = new ListNode(0); ListNode p = res; if(p1 == null && p2 == null){ return null; } while(p1 != null || p2 != null
){ int a = p1 != null ? p1.val:Int32.MaxValue; int b = p2 != null ? p2.val:Int32.MaxValue; int min = a<b?a:b; if(p1!= null && min == p1.val){ ListNode temp = new ListNode(min); p.next = temp; p
= p.next; p1 = p1.next; } if(p2!=null && min == p2.val){ ListNode temp = new ListNode(min); p.next = temp; p = p.next; p2 = p2.next; } } return res.next; } }

0009 合並兩個有序鏈表