LeeCode (recursion, iteration) 21_ merge two ordered linked lists

LeeCode (recursion, iteration) 21_ merge two ordered linked lists

Topic:
Combine two ascending linked lists into a new ascending linked list and return. The new linked list is composed by splicing all the nodes of the given two linked lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

Source: LeetCode
Link: https://leetcode-cn.com/problems/merge-two-sorted-lists
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Problem-solving idea:
first determine which of the head nodes of l1 and l2 is smaller, use it as the first node of the synthesized linked list, and then recursively determine the next node with a smaller value.

Method one:
recursion

Java code:


class ListNode {
    
    
	 int val;
     ListNode next;
     ListNode() {
    
    }
     ListNode(int val) {
    
     this.val = val; }
     ListNode(int val, ListNode next) {
    
     this.val = val; this.next = next; }
 }

public class 合并两个有序链表 {
    
    

	public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    
    
		if(l1==null){
    
    
			return l2;
		}else if(l2==null){
    
    
			return l1;
		}else if(l1.val<l2.val){
    
    
			l1.next = mergeTwoLists(l1.next, l2);
			return l1;
		}else {
    
    
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }
		
	}

	
	public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    
    
		ListNode prehead = new ListNode();
		//保存链表头
		ListNode prev = prehead;
		while(l1!=null && l2!=null){
    
    
			if(l1.val<l2.val){
    
    
				prehead.next = l1;
				l1 = l1.next;
			}else {
    
    
                prev.next = l2;
                l2 = l2.next;
            }
		}
		
		// 合并后 l1 和 l2 最多只有一个还未被合并完,我们直接将链表末尾指向未合并完的链表即可
        prev.next = l1 == null ? l2 : l1;
		
		return prev.next;
	}	
}

Method two:
iteration


class ListNode {
    
    
	 int val;
     ListNode next;
     ListNode() {
    
    }
     ListNode(int val) {
    
     this.val = val; }
     ListNode(int val, ListNode next) {
    
     this.val = val; this.next = next; }
 }

public class 合并两个有序链表 {
    
    
	
	public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    
    
		ListNode prehead = new ListNode();
		//保存链表头
		ListNode prev = prehead;
		while(l1!=null && l2!=null){
    
    
			if(l1.val<l2.val){
    
    
				prehead.next = l1;
				l1 = l1.next;
			}else {
    
    
                prev.next = l2;
                l2 = l2.next;
            }
		}
		
		// 合并后 l1 和 l2 最多只有一个还未被合并完,我们直接将链表末尾指向未合并完的链表即可
        prev.next = l1 == null ? l2 : l1;
		
		return prev.next;
	}	
}

Guess you like

Origin blog.csdn.net/u013456390/article/details/112169624