有序单链表合并和单链表反转

//递归的方法
LinkList mergeTwoList2(LinkList l1,LinkList l2)
{
	if(l1 == NULL)
	{
		return l2;	
	}	
	if(l2 == NULL)
	{
		return l1;
	}
	else if(l1->data <= l2->data)
	{
		l1->next = mergeTwoList2(l1->next, l2);
		return l1;
	}
	else
	{
		l2->next = mergeTwoList2(l1,l2->next);
		return l2;
	}
} 
//迭代
//迭代 
LinkList mergeTwoList1(LinkList La, LinkList Lb)
{
	LinkList prehead = new Lnode;
	prehead->next = NULL;
	Lnode* prev = prehead;
	while (La != NULL && Lb != NULL) {
        if (La->data <= Lb->data) 
		{
        	prev->next = La;
            La = La->next;
        }
		else
		{
            prev->next = Lb;
            Lb = Lb->next;
        }
            prev = prev->next;
        }

        // 合并后 l1 和 l2 最多只有一个还未被合并完,我们直接将链表末尾指向未合并完的链表即可
        prev->next = (La == NULL) ? Lb : La;
        cout<<prev->data<<endl;
        cout<<prehead->data<<endl;
        cout<<prehead->next->data<<endl;
        return prehead->next->next;
} 
//前指针反转
struct ListNode* reverseList(struct ListNode* head){
    if(head == NULL || head->next == NULL)
        return head;
    struct ListNode* newhead =  NULL;
    struct ListNode* cur = head;
    struct ListNode* temp;
    
    while(cur != NULL)
    {
        //将当前节点的下节点保存下来
        temp = cur->next;
        cur->next = newhead;
        newhead = cur;

        cur = temp;
    }
    return newhead;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值