演算法22 leetcode合併兩個有序連結串列
阿新 • • 發佈:2021-11-24
題目
將兩個升序連結串列合併為一個新的 升序 連結串列並返回。新連結串列是通過拼接給定的兩個連結串列的所有節點組成的。
示例 1:
輸入:l1 = [1,2,4], l2 = [1,3,4]
輸出:[1,1,2,3,4,4]
示例 2:
輸入:l1 = [], l2 = []
輸出:[]
示例 3:
輸入:l1 = [], l2 = [0]
輸出:[0]
提示:
- 兩個連結串列的節點數目範圍是 [0, 50]
- -100 <= Node.val <= 100
- l1 和 l2 均按 非遞減順序 排列
連結:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnnbp2/
來源:力扣(LeetCode)
程式碼
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1==null||l2==null) return l2==null ? l1:l2; ListNode tmp =l1;//l1插入l2 while(tmp!=null){ l2=ckadd(tmp,l2); tmp =tmp.next; } return l2; } ListNode ckadd(ListNode node,ListNode l2){ ListNode mm=new ListNode(0,l2); ListNode fh=mm; while(node.val>l2.val){ mm=l2; l2=l2.next; if(l2==null){ mm.next=new ListNode(node.val,null); return fh.next; } } mm.next=new ListNode(node.val,l2); return fh.next; } }
遞迴方式
public ListNode mergeTwoLists(ListNode linked1, ListNode linked2) { //只要有一個為空,就返回另一個 if (linked1 == null || linked2 == null) return linked2 == null ? linked1 : linked2; //把小的賦值給first ListNode first = (linked2.val < linked1.val) ? linked2 : linked1; first.next = mergeTwoLists(first.next, first == linked1 ? linked2 : linked1); return first; }