Problem:
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.
Analysis:
题意:合并两个排序链表并返回一个新的列表。新列表应该由拼接在一起的前两个列表的节点进行。
两个链表合并,需要考虑比较每个链表的头节点大小,还要考虑不同长度的两个链表的情况。
Anwser:
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode headNode = new ListNode(0);
ListNode p = headNode;
while(l1!=null && l2!=null){
if(l1.val<l2.val) {
p.next = l1;
l1 = l1.next;
}
else{
p.next = l2;
l2 = l2.next;
}
p = p.next;
}
if(l2 != null){
p.next = l2;
p = p.next;
}
if(l1 != null){
p.next = l1;
p = p.next;
}
return headNode.next;
}
}
注意:
- l.val不能和null进行比较。
- 应该有个头结点,便于返回链表的head