链表的中间节点和判断链表是否为环形链表

基本思想:

设置两个指针,都指向链表的头节点。两个指针同时从链表的头节点出发,一个指针每次走一步,另一个指针每次走两步。

1.走得快的指针走到链表末尾时,走得慢的指针刚好指向链表的中间节点。

2.走得快的指针如果追的上走得慢的指针,则链表为环形链表,反之不是。

代码如下:

#include <iostream>
#include <stdexcept>
using namespace std;
struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x):val(x),next(NULL){}
};
bool IsCircleList(ListNode *pHead)
{
    ListNode *p1=pHead;
    ListNode *p2=pHead;

    if(pHead==NULL||pHead->next==NULL) throw runtime_error("List is NULL");

    while(p2->next!=NULL&&p2->next->next!=NULL)
    {
        p1=p1->next;
        p2=p2->next->next;
        if(p2==p1)
        {
            return true;
        }
    }
    return false;
}
ListNode *MiddleofList(ListNode *pHead)
{
    ListNode *p1=pHead;
    ListNode *p2=pHead;

    if(pHead==NULL) throw runtime_error("List is NULL");
    if(IsCircleList(pHead)) throw runtime_error("List is circle"); 

    while(p2->next!=NULL&&p2->next->next!=NULL)
    {
        p1=p1->next;
        p2=p2->next->next;
    }
    return p1;
}
int main()
{
    ListNode *n1=new ListNode(1);
    ListNode *n2=new ListNode(2);
    ListNode *n4=new ListNode(4);
    ListNode *n5=new ListNode(5);
    n1->next=n2;
    n2->next=n4;
    n4->next=n5;
//  n5->next=n1;

    ListNode *res=MiddleofList(n1);
    cout<<IsCircleList(n1)<<endl;
//  cout<<res->val<<endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值