问题描述:
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.
思考:
最开始以为就是两个链表简答的合并就ok,自己确实差啊,后来想想有些细节,合并后的链表是递增的,每次添加的节点是两个链表中当前节点的最小值,还有就是两个链表也不一定相等。
代码(java):
public class MergeTwoSortedLists {
static public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null && l2 == null){
return null;
}
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}
ListNode current,left,right,head;//current是最近添加的节点,也就是当前工作节点,head表示头结点
left = l1;
right = l2;
//找一个最小值作为头结点,假设两个链表都是有序链表,所以l1和l2都是所在链表的最小值
if(l1.val<= l2.val){
head = l1;
left = left.next;
}
else{
head = l2;
right = right.next;
}
current = head;
//寻找right和left的小值作为当前节点的下一个节点
while(left != null && right != null){
if(left.val <= right.val ){
current.next = left;
current = left;
left = left.next;
}
else{
current.next = right;
current = right;
right = right.next;
}
}
if(left == null){
while(right != null){
current.next = right;
current = right;
right = right.next;
}
}
if(right == null){
while(left != null){
current.next = left;
current = left;
left = left.next;
}
}
return head;
}
}