问题描述
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 ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode cur = head;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
cur.next = l1;
l1 = l1.next;
} else {
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
if (l1 == null) {
cur.next = l2;
}
if (l2 == null) {
cur.next = l1;
}
return head.next;
}
网友评论