描述
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.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
难度
Easy
题目链接:
https://leetcode.com/problems/merge-two-sorted-lists/
思路
合并两个有序链表,重点在 while 循环中,前面增加了两个判断,主要是因为两个链表一起遍历,可能其中一个已经遍历完毕了,此时将另一个链表拼到结果链表后面即可。
正常的逻辑是 if 语句,主要是判断当前两个结点的大小,然后决定哪个链表向后移动一位。
public static void main(String...args) {
ListNode l1 = new ListNode(1);
ListNode l12 = new ListNode(2);
ListNode l13 = new ListNode(4);
ListNode l14 = new ListNode(5);
l1.next = l12;
l12.next = l13;
l13.next = l14;
ListNode l2 = new ListNode(1);
ListNode l22 = new ListNode(3);
ListNode l23 = new ListNode(4);
ListNode l24 = new ListNode(6);
l2.next = l22;
l22.next = l23;
l23.next = l24;
ListNode ret = mergeTwoLists(l1, l2);
System.out.println(ret);
}
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode node = new ListNode(0), head = node;
while (l1 != null || l2 != null) {
if (l1 == null) {
node.next = l2;
break;
}
if (l2 == null) {
node.next = l1;
break;
}
if (l1.val > l2.val) {
node.next = l2;
l2 = l2.next;
} else {
node.next = l1;
l1 = l1.next;
}
node = node.next;
}
return head.next;
}
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
虽然上面的程序可以解决问题,但是,显然,不够优雅和简练!