数据结构:单链表操作之如何判断链表是否带环及相关操作

来源:互联网 发布:财达大智慧软件下载 编辑:程序博客网 时间:2024/05/29 17:49

//判断链表是否有环


int HasCircle(Node* pHead)
{
Node* low=pHead;
Node* fast=pHead;
    while(fast != NULL && fast->next != NULL)
    {
        low=low->next;
        fast=fast->next->next;
        if(low==fast) 
return 1;
}
    return 0;
}

时间复杂度:O(1)

//求环中快慢指针相遇节点
Node* HasCircle(Node* pHead)
{
Node* low=pHead;
Node* fast=pHead;
    if(pHead==NULL) 
return NULL;
    while(fast != NULL && fast->next != NULL)
    {
        low=low->next;
        fast=fast->next->next;
        if(low==fast) 
return low;
}
    return NULL;
}
//求环长度
int GetCircleLen(Node* pMeetNode)
{
Node* Node = pMeetNode->next;


int lenght = 1;
while(Node != pMeetNode )
{
lenght++;
Node = Node->next;
}
return lenght;
}

时间复杂度:O(1)

//求环的入口
Node* GetEnterNode(Node* pHead, Node* pMeetNode)
{
Node* start = pHead;
if(pHead == NULL)
return NULL;

while(start != pMeetNode)
{
start = start->next;
pMeetNode = pMeetNode->next;
}
return start;
}


时间复杂度:O(1)

阅读全文
0 0
原创粉丝点击