[Linked List OJ] Merge two ordered linked lists

click me to do the question

Please see the topic:

Merges two ascending lists into a new  ascending  list and returns. The new linked list is formed by splicing all the nodes of the given two linked lists. 

Example 1: 

Input: l1 = [1,2,4], l2 = [1,3,4]
 Output: [1,1,2,3,4,4]

Example 2: 

Input: l1 = [], l2 = []
 Output: []

Example 3:

Input: l1 = [], l2 = [0]
 Output: [0]

Problem solving: 

Ideas: 

Since the given two linked lists are in ascending order, compare the values ​​of the two linked lists from the beginning, and the smaller one will be the first. In order to facilitate finding the previous value, you can create a dummy node to represent the previous node. The animation is as follows :

Code:

struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){
    // 创建哑结点
    struct ListNode {
    int val = -1;
    struct ListNode *next;
    }dummy;
    // 表示前一个结点
    struct ListNode* prev = &dummy;
    // 二者均非空,则进行比较
    while(list1 && list2)
    {
        if(list1->val < list2->val)
        {
            prev->next = list1;
            list1 = list1->next;
        }
        else
        {
            prev->next = list2;
            list2 = list2->next;
        }
        prev = prev->next;
    }
    prev->next = list1 == NULL?list2:list1;
    return dummy->next;
}

This article is over.

Guess you like

Origin blog.csdn.net/Claffic/article/details/130189732