21 - Merge Two Sorted Lists - LeetCode

本文详细阐述了如何使用链表实现归并排序的merge过程,包括递归和迭代两种方法,并提供了一段较为复杂的自定义代码实例。通过简化操作,优化了归并链表的效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

分析:

就是归并排序的merge过程,只不过用链表实现了。

可以递归进行,也可以迭代。

自己的代码又臭又长,但也要记录下来。后面附上比较优秀的代码。

mine:

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if(!l1)
            return l2;
        if(!l2)
            return l1;
       
        ListNode* current1, *current2;
        current1 = l1; current2 = l2;
        
        ListNode* head;
        if(l1->val > l2->val)	{
			head = l2;
			current2 = current2->next;
		} else {
			head = l1;
			current1 = current1->next;
		}
			
		ListNode* p = head;
		
        while(current1 && current2) {
            if(current1->val > current2->val)  {
				p->next = current2;
				current2 = current2->next;  
			
            } 
            else{
            	p->next = current1;
				current1 = current1->next;         	 	
            }
             
            p = p->next;
            
        }
        
        if(current1)    p->next = current1;
        if(current2)    p->next = current2;
        
        return head;
    }
};

简洁代码:—— 增加头结点,省了很多事儿。

class Solution {
public:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        //为操作方便,添加一个头节点
        ListNode node(0), *p = &node;
        while(l1 && l2)
        {
            if(l1->val < l2->val)
            {
                p->next = l1;
                l1 = l1->next;
            }
            else
            {
                p->next = l2;
                l2 = l2->next;
            }
            p = p->next;
        }
        if(l1)p->next = l1;
        else if(l2)p->next = l2;
        return node.next;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值