题解 | #合并两个排序的链表#注意异常情况的处理
合并两个排序的链表
http://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1 == null) return list2;
if(list2 == null) return list1;
ListNode res = null,resTail = null;
ListNode node1 = list1, node2 = list2;
if(list1.val < list2.val){
res = list1;
node1 = node1.next;
}else{
res = list2;
node2 = node2.next;
}
resTail = res;
while(node1 != null && node2 !=null){
if(node1.val<node2.val){
resTail.next = node1;
resTail = resTail.next;
node1 = node1.next;
}else{
resTail.next = node2;
resTail = resTail.next;
node2 = node2.next;
}
}
if(node1 == null){
resTail.next = node2;
}else if(node2 == null){
resTail.next = node1;
}
return res;
}
}
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1 == null) return list2;
if(list2 == null) return list1;
ListNode res = null,resTail = null;
ListNode node1 = list1, node2 = list2;
if(list1.val < list2.val){
res = list1;
node1 = node1.next;
}else{
res = list2;
node2 = node2.next;
}
resTail = res;
while(node1 != null && node2 !=null){
if(node1.val<node2.val){
resTail.next = node1;
resTail = resTail.next;
node1 = node1.next;
}else{
resTail.next = node2;
resTail = resTail.next;
node2 = node2.next;
}
}
if(node1 == null){
resTail.next = node2;
}else if(node2 == null){
resTail.next = node1;
}
return res;
}
}