165. Merge Two Sorted Lists【LintCode by java】
阿新 • • 發佈:2018-06-02
-i get In param des AD end itl spl
Description
Merge two sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should be made by splicing together the nodes of the two lists and sorted in ascending order.
Example
Given 1->3->8->11->15->null
, 2->null
, return 1->2->3->8->11->15->null
.
解題:很經典的一道題目,有序鏈表的合並。LintCode中鏈表默認沒有頭指針,不過此題可以構造一個帶頭結點的鏈表存放結果,最後返回的時候把頭結點去掉即可。代碼如下:
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param l1: ListNode l1 is the head of the linked list
* @param l2: ListNode l2 is the head of the linked list
* @return: ListNode head of linked list
*/
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
// write your code here
ListNode nhead = new ListNode(0);
ListNode rear = nhead;
while(l1 != null && l2 != null){
if(l1.val < l2.val){
rear.next = l1;
l1 = l1.next;
}else{
rear.next = l2;
l2 = l2.next;
}
rear = rear.next;
rear.next = null;
}
if(l1 != null){
rear.next = l1;
}else{
rear.next = l2;
}
return nhead.next; //關鍵
}
}
165. Merge Two Sorted Lists【LintCode by java】