本文主要記錄一下leetcode鏈表之合併兩個排序的鏈表網絡
輸入兩個遞增排序的鏈表,合併這兩個鏈表並使新鏈表中的節點仍然是遞增排序的。 示例1: 輸入:1->2->4, 1->3->4 輸出:1->1->2->3->4->4 限制: 0 <= 鏈表長度 <= 1000 來源:力扣(LeetCode) 連接:https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof 著做權歸領釦網絡全部。商業轉載請聯繫官方受權,非商業轉載請註明出處。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode newHead = new ListNode(-1); ListNode cursor = newHead; while(l1 != null && l2 != null) { if (l1.val <= l2.val) { cursor.next = l1; l1 = l1.next; } else { cursor.next = l2; l2 = l2.next; } cursor = cursor.next; } if (l1 == null) { cursor.next = l2; } if (l2 == null) { cursor.next = l1; } return newHead.next; } }
合併兩個有序鏈表的基本思路就是設置一個cursor以及新鏈表的頭指針,而後同時遍歷兩個鏈表,取小的節點做爲cursor的next,而後該鏈表往前進,cursor也跟着往前進,最後再將cursor.next指向還沒有遍歷完的鏈表的剩餘節點指針