將兩個升序鏈表合并為一個新的?升序?鏈表并返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。?
思路:這里使用的主要數據結構是單鏈表。該算法采用經典的雙指針技術來合并列表。
- A dummy node is created; this node does not hold any meaningful value but serves as the starting point of the merged?linked list.
將創建一個虛擬節點;此節點不包含任何有意義的值,但用作合并鏈表的起點。 - A?
curr
?pointer is initialized to point at the dummy node. This pointer moves along the new list as nodes are added.
curr
?指針初始化為指向虛擬節點。添加節點時,此指針會沿新列表移動。
/*** 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 list1, ListNode list2) {ListNode dummyHead = new ListNode();ListNode current = dummyHead;while (list1!= null&& list2!=null){if(list1.val<=list2.val){current.next=list1;list1=list1.next;}else{current.next=list2;list2=list2.next;}current=current.next;}current.next=(list1==null)?list2:list1;return dummyHead.next;}
}