Niuke.com Brushing Questions-Merging Ordered Linked Lists

Problem Description

Merging two ordered linked lists into a new linked list requires that the new linked list is generated by splicing the nodes of the two linked lists, and the new linked list is still in order after the merger.

Input description:
Input two linked lists

Output description:
output sorted linked list

Example

Example 1

Enter
{1},{2}

Output
{1,2}

Solutions

analysis

  1. Add an extra node by comparing two nodes, and then add nodes to this extra node at a time.

method

  1. Add an extra node by comparing two nodes, and then add nodes to this extra node at a time.

Code

// 思路1
public class Solution {
    
    
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    
    
        // write code here
        if (l1 == null) {
    
    
            return l2;
        }
        if (l2 == null) {
    
    
            return l1;
        }

        ListNode l0 = new ListNode(0);
        ListNode cur = l0;
        while (l1 != null && l2 != null) {
    
    
            if (l1.val < l2.val) {
    
    
                cur.next = l1;
                l1 = l1.next;
            } else if (l1.val >= l2.val) {
    
    
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }

        if (l1 != null) {
    
    
            cur.next = l1;
        }

        if (l2 != null) {
    
    
            cur.next = l2;
        }

        return l0.next;
    }

}

If you want to test, you can go directly to the link of Niuke.com to do the test

Merging ordered linked lists-niuke.com

Guess you like

Origin blog.csdn.net/qq_35398517/article/details/113361480