標籤:歸併 單鏈表 演算法 面試 offer
【021-Merge Two Sorted Lists(合并兩個排好序的單鏈表)】
【LeetCode-面試演算法經典-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.
題目大意
合并兩個排序鏈表並返回一個新的列表。新的鏈表的結果由原先的兩個鏈表結點組成,也就是不能合并後的鏈表不能包含新建立的結點。
解題思路
使用頭結點root進行輔助操作,建立一個頭結點,再使用兩個引用指向兩個鏈表的頭結點,將較小的結點值的結點摘下來接到root鏈表的末尾,同時被摘的鏈頭引用移動到下一個結點,一直操作,到到原先兩個鏈表中有一個為空白,最後再將剩下的結點接到root鏈表的末尾。最後返回root的下一個結點,其就為新的鏈表頭。
代碼實現
鏈表結點類
public class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; }}
演算法實作類別
public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode head = new ListNode(0); // 建立一個頭結點,最後還要刪除掉 ListNode tail = head; while (l1 != null && l2 != null) { if (l1.val <= l2.val) { tail.next = l1; l1 = l1.next; } else { tail.next = l2; l2 = l2.next; } tail = tail.next; // 移動到新的尾結點 } tail.next = (l1 != null ? l1 : l2); return head.next; // head的下一個節點是第一個資料結點 }}
評測結果
點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。
特別說明
歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/47016121】
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
【LeetCode-面試演算法經典-Java實現】【021-Merge Two Sorted Lists(合并兩個排好序的單鏈表)】