题目描述:
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.
解题思路:
题目的意思是将两个有序链表合成一个有序链表。
逐个比较加入到新的链表即可。
代码如下:
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode list = new ListNode(0); ListNode tmp = list; while (l1 != null || l2 != null) { if (l1 == null) { tmp.next = new ListNode(l2.val); l2 = l2.next; } else if (l2 == null) { tmp.next = new ListNode(l1.val); l1 = l1.next; } else { if (l1.val < l2.val) { tmp.next = new ListNode(l1.val); l1 = l1.next; } else { tmp.next = new ListNode(l2.val); l2 = l2.next; } } tmp = tmp.next; } return list.next; }
时间: 2024-10-07 01:24:50