21. Merge two ordered linked lists (simple)

Ideas:

Create a new linked list, compare the first node of the two linked lists passed in, and transfer the smaller value to the new linked list

The key is to create two pointers when declaring a new linked list , one finger and one change with the process

Also create a pointer that changes with the process for each of the two linked lists passed in

 

class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1==null||l2==null){
            return l1==null?l2:l1;
        }
		ListNode head=new ListNode(0);
		ListNode tail=head;
		ListNode res1=l1;
		ListNode res2=l2;
		
		while(res1!=null&&res2!=null){
			if(res1.val<res2.val){
				tail.next=res1;
				res1=res1.next;
			}
			else{
				tail.next=res2;
				res2=res2.next;
			}
            tail=tail.next;
		}
		if(res1==null){
			tail.next=res2;
			
		}
		
		if(res2==null){
			tail.next=res1;
		}
		
		return head.next;
    }
}

break down:

            if(res1==null){
		tail.next=res2;		
	    }
		
	    if(res2==null){
		tail.next=res1;
	    }

1) The above code simplifies the ternary expression:

tail.next=res1==null?res2:res1;

 

2) Two pointers of the new linked list: head and tail

Pointers of l1 and l2: res1 and res2

Guess you like

Origin blog.csdn.net/di_ko/article/details/115062966