【LeetCode-面試演算法經典-Java實現】【021-Merge Two Sorted Lists(合并兩個排好序的單鏈表)】

來源:互聯網
上載者:User

標籤:歸併   單鏈表   演算法   面試   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(合并兩個排好序的單鏈表)】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.