算法--合并两个有序链表

      有两种方法,迭代和递归。

      迭代:

//不带头结点
Node * Merge(Node *head1 , Node *head2){
	//判空
	if ( head1 == NULL)
		return head2 ;
	if ( head2 == NULL)
		return head1 ;

	//头结点
	Node *head = NULL ;

	//分别指向两个链表
	Node *p1 = NULL;
	Node *p2 = NULL;

	//head指向较小值的那个链表
	if ( head1->data < head2->data )
	{
		head = head1 ;
		p1 = head1->next;
		p2 = head2 ;
	}else{
		head = head2 ;
		p2 = head2->next ;
		p1 = head1 ;
	}

	//当前排序好的链表的末尾节点
	Node *pcurrent = head ;
	while ( p1 != NULL && p2 != NULL)
	{
		if ( p1->data <= p2->data )
		{
			pcurrent->next = p1 ;
			pcurrent = p1 ;
			p1 = p1->next ;
		}
		else
		{
			pcurrent->next = p2 ;
			pcurrent = p2 ;
			p2 = p2->next ;
		}
	}

	//还有一方没有遍历完的情况
	if ( p1 != NULL )
		pcurrent->next = p1 ;
	if ( p2 != NULL )
		pcurrent->next = p2 ;
	
	return head ;
}

时间复杂度:O(n+m),m和n分别为两个链表的长度,因为两个链表都要遍历到

空间复杂度:O(1)

 

递归:

Node * MergeRecursive(Node *head1 , Node *head2){
	//判空
	if ( head1 == NULL )
		return head2 ;
	if ( head2 == NULL)
		return head1 ;
	
	Node *head = NULL ;
	if ( head1->data < head2->data ){
		head = head1 ;
		//每次递归都返回head->next,head表示当前节点,一个局部变量
		head->next = MergeRecursive(head1->next,head2);
	}else{
		head = head2 ;
		head->next = MergeRecursive(head1,head2->next);
	}
	return head ;
}

时间复杂度:O(n+m),每个节点都要遍历到

空间复杂度:O(n+m),递归需要消耗栈空间,大小就是m+n

 

力扣的迭代代码更为简洁

ListNode* mergeTwoLists(ListNode *a, ListNode *b) {
    if ((!a) || (!b)) return a ? a : b;
    ListNode head, *tail = &head, *aPtr = a, *bPtr = b;
    while (aPtr && bPtr) {
        if (aPtr->val < bPtr->val) {
            tail->next = aPtr; aPtr = aPtr->next;
        } else {
            tail->next = bPtr; bPtr = bPtr->next;
        }
        tail = tail->next;
    }
    tail->next = (aPtr ? aPtr : bPtr);
    return head.next;
}


 

代码地址:https://www.cnblogs.com/fangyukuan/archive/2010/09/18/1829871.html

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

盼盼编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值