Java [leetcode 21]Merge Two Sorted Lists
题目描述:
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; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。