[LeetCode]--21. Merge Two Sorted Lists

    xiaoxiao2026-02-15  15

    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.

    这里sorted说的是从小到大。

    /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode ln = new ListNode(0); ListNode temp = ln; while (l1 != null && l2 != null) { if (l1.val<l2.val) { temp.next = l1; l1 = l1.next; } else { temp.next = l2; l2 = l2.next; } temp = temp.next; } if (l1 == null && l2 != null) { temp.next = l2; } if (l2 == null && l1 != null) { temp.next = l1; } return ln.next; } }

    再看下别人写的代码,其实差不多,这种一般都会采用插入排序。

    ListNode dummy = new ListNode(0); ListNode lastNode = dummy; while (l1 != null && l2 != null) { if (l1.val < l2.val) { lastNode.next = l1; l1 = l1.next; } else { lastNode.next = l2; l2 = l2.next; } lastNode = lastNode.next; } if (l1 != null) { lastNode.next = l1; } else { lastNode.next = l2; } return dummy.next;
    最新回复(0)