The sword refers to offer--17. Merge two sorted linked lists

Question: Input two linked lists in ascending order, merge the two linked lists and make the nodes in the new linked list still in ascending order

Ideas: recursive and non-recursive methods, but pay attention to the processing of special input (empty linked list)

public class wr17mergeListNode {
// recurse
	public ListNode Merge(ListNode list1,ListNode list2){
		if(list1==null){
			return list2;
		}
		else if(list2==null){
			return list1;
		}
		ListNode newhead=new ListNode();
		if(list1.val<list2.val){
			newhead=list1;
			newhead.next=Merge(list1.next,list2);
		}
		else{
			newhead=list2;
			newhead.next=Merge(list1,list2.next);
		}
		return newhead;
	}
// non-recursive
	public ListNode mergeList(ListNode list1,ListNode list2){
		if(list1==null){
			return list2;
		}
		else if(list2==null){
			return list1;
		}
		
		ListNode head=null;
		ListNode current=head;
		while(list1!=null && list2!=null){
			if(list1.val<list2.val){
				if(head==null){
					head=list1;
					current=list1;
				}else{
					current.next=list1;
					current=current.next;
				}
				list1=list1.next;
			}else{
				if(head==null){
					head=list2;
					current=list2;
				}else{
					current.next=list2;
					current=current.next;
				}
				list2=list2.next;
			}
		}
		if(list1!=null){
			current.next=list1;
		}
		if(list2!=null){
			current.next=list2;
		}
		return head;
	}
}

Guess you like

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