题目描述:

当两个链表都为空则返回空,存在一个为空返回另一个。
思路:
将两个有序链表合并为一个,将各个节点按照大小顺序串起来。定义一个节点作为合并后链表的头部:head,无实际意义,单纯的当作合并头节点。还需一个中间量temp=head。在添加节点的过程中,head不变,temp需要一直保持链表尾部。比较list1和list2的大小,temp.next=min(list1.val,list2.val),将较小的向后移动,min(list1.val,list2.val)=min(list1.val,list2.val).next,并且移动temp=temp.next。当其中一个链表为空后,推出循环,将剩余节点加到新链表尾部,temp.next=(list1==null)?list2:list1。最后返回的头节点为head.next。

代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if(list1==null && list2==null){
return null;
}
ListNode head=new ListNode();
ListNode temp=head;
while(list1!=null && list2!=null){
if(list1.val<list2.val){
temp.next=list1;
list1=list1.next;
temp=temp.next;
}else{
temp.next=list2;
list2=list2.next;
temp=temp.next;
}
}
if(list1==null){
temp.next=list2;
}else{
temp.next=list1;
}
return head.next;
}
}
612

被折叠的 条评论
为什么被折叠?



