1. 程式人生 > >java 合併兩個排序的連結串列

java 合併兩個排序的連結串列

題目:

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.

演算法如下:

/**
 * 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) { ListNode head = null; if(l1==null&&l2==null){ return null; } if(l1==null){ return l2; } if(l2==null){ return l1; } if
(l1.val<l2.val){ head = l1; l1 = l1.next; }else{ head = l2; l2 = l2.next; } ListNode newHead = head; while(l1!=null&&l2!=null){ while(l1.val<l2.val){ head.next = l1; head = head.next; l1 = l1.next; if
(l1==null||l2==null) break; } if(l1==null||l2==null) break; while(l1.val>=l2.val){ head.next = l2; head = head.next; l2 = l2.next; if(l2==null||l1==null) break; } } while(l1!=null){ head.next = l1; head = head.next; l1 = l1.next; } while(l2!=null){ head.next = l2; head = head.next; l2 = l2.next; } return newHead; } }