链表相关算法

1.链表反转

递归算法

ListNode* reverselist(ListNode *head)
{
    if(head==NULL or head->next==NULL)
        return head;
    ListNode *p=reverselist(head->next);
    head->next->next=head;
    head=NULL;
    return p;
}

非递归算法

ListNode* reverselist(ListNode *head)
{
    ListNode *cur=head;
    if(cur==NULL)
        return cur;
    ListNode *pre=NULL;
    while(cur!=NULL)
    {
        temp=cur->next;
        cur->next=pre;
        pre=cur;
        cur=temp;
    }
    return pre;
}

2.单链表是否有环

bool hasCycle(ListNode *head)

{

    if(head==NULL or head->next==NULL)

        return false;

    ListNode *fast,*slow;

    slow=head;

    fast=head->next;

    while(fast&&fast->next)

    {

        slow=slow->next;

        fast=fast->next->next;

        if(slow==fast)

            return true;

    }

    return false;

}

3.单链表找环入口

ListNode* detectCycle(ListNode *head)

{

    if(head==NULL)

        return head;

    ListNode *fast,*slow;

    slow=head;

    fast=head;

    while(fast&&fast->next)

    {

        slow=slow->next;

        fast=fast->next->next;

        if(slow==fast)

        {

            ListNode *slow2=head;

            while(slow2!=slow)

            {

                slow=slow->next;

                slow2=slow2->next;

            }

            return slow2;

        }

    }

    return null;

}

 

4.单链表找交点

ListNode *getIntersectionNode(ListNode *headA,ListNode *headB)

{

    ListNode *pa=headA;

    ListNode *pb=headB;

    while(pa!=pb)

    {

        pa=pa!=NULL?pa->next:headB;

        pb=pb!=NULL?pb->next:headA;

    }

    return pa;

}

5.链表找中间点

ListNode* middleNode(ListNode *head)

{

    ListNode *slow=head;

    ListNode *fast=head;

    while(fast&&fast->next)

    {

        slow=slow->next;

        fast=fast->next->next;

    }

    return slow;

}

6.已排序链表合并

ListNode *mergeTwoLists(ListNode *l1,ListNode *l2)

{

    if(l1==NULL)

        return l2;

    if(l2==NULL)

        return l1;



    ListNode dummy(-1);

    ListNode *p=&dummy;

    for(;l1&&l2;p=p->next)

    {

        if(l1->val<l2->val)

        {

            p->next=l1;

            l1=l1->next;

        }

        else

        {

            p->next=l2;

            l2=l2->next;

        }

    }

    p->next=l1!=NULL?l1:l2;

    return dummy.next;

}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值