剑指offer--合并两个排序的链表

public ListNode Merge(ListNode list1,ListNode list2) {
        if(list1==null&&list2==null) {
        	return null;
        }
        if(list1==null) {
        	return list2;
        }
        if(list2==null) {
        	return list1;
        }
        ListNode head = new ListNode(-1);
        ListNode current = head;//指向一个新节点
        while(list1!=null&&list2!=null) {
        	if(list1.val < list2.val) {
        		current.next = list1;
        		current = current.next;
        		list1 = list1.next;
        	}else {
        		current.next = list2;
        		current = current.next;
        		list2 = list2.next;
        	}
        }
        //将剩余的添加进入新节点
        if(list1!=null) {
        	current.next = list1;
        }
        if(list2!=null) {
        	current.next = list2;
        }
        
		return head.next;
    }

  

猜你喜欢

转载自www.cnblogs.com/zhaohuan1996/p/8961959.html