算法题笔记-easy难度-06合并两个有序链表(leetcode第21题)

139 阅读1分钟

题目地址:leetcode-cn.com/problems/me…

思路:每次取出两个链表中的第一个元素,进行比较。将较小的那个元素插入新链表。一直到某一个链表走完以后,将剩余链表的剩余值插到新链表上。

上代码:

/**
 * 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 headNode = new ListNode(0);

        ListNode newListNode = headNode;
        while (list1 != null && list2 != null) {
            if (list1.val < list2.val) {
                newListNode.next = list1;
                list1 = list1.next;
            } else {
                newListNode.next = list2;
                list2 = list2.next;
            }
            newListNode = newListNode.next;
        }
        newListNode.next = list1 == null?list2:list1;
        return headNode.next;
    }
}