leetcode21题解

2025-10-23

Leetcode21

题目描述

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

思路

简单的数据结构小题目,做做玩得了

代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        if(list1==NULL && list2==NULL) return NULL;
        else{
            ListNode* p1,*p2,*pr;
            p1=list1;
            p2=list2;
            ListNode* res=new ListNode();
            pr=NULL;
            
            while(1){
                if(p1==NULL && p2==NULL) break;
                else
                {
                    if(pr==NULL) pr=res;
                    else pr=pr->next;

                    if(p1==NULL){
                        pr->val=p2->val;
                        pr->next=new ListNode();
                        p2=p2->next;
                    }
                    else if(p2==NULL){
                        pr->val=p1->val;
                        pr->next=new ListNode();
                        p1=p1->next;
                    }
                    else {
                        if(p1->val<p2->val){
                            pr->val=p1->val;
                            pr->next=new ListNode();
                            p1=p1->next;
                        }
                        else{
                            pr->val=p2->val;
                            pr->next=new ListNode();
                            p2=p2->next;
                        }
                    }
                    
                }

            }
            delete pr->next;
            pr->next=NULL;
            return res;
        }
    }
};