21.合并两个有序链表

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

思路:这里使用的主要数据结构是单链表。该算法采用经典的双指针技术来合并列表。

  1. A dummy node is created; this node does not hold any meaningful value but serves as the starting point of the merged linked list.
    将创建一个虚拟节点;此节点不包含任何有意义的值,但用作合并链表的起点。
  2. 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;
    }
}

你可能感兴趣的:(算法题,链表,数据结构)