Sword refers to offer--merge two sorted linked lists

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;//Point to a new node
        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;
        	}
        }
        //Add the rest to the new node
        if(list1!=null) {
        	current.next = list1;
        }
        if(list2!=null) {
        	current.next = list2;
        }
        
		return head.next;
    }

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325011599&siteId=291194637