C++笔试题之判断链表中是否有环,并计算环的长度

版权声明:本文为灿哥哥http://blog.csdn.net/caoshangpa原创文章,转载请标明出处。 https://blog.csdn.net/caoshangpa/article/details/80363335
       判断链表中是否有环最经典的方法就是快慢指针,同时也是面试官大多想要得到的答案。
       快指针pf(f就是fast的缩写)每次移动2个节点,慢指针ps(s为slow的缩写)每次移动1个节点,如果快指针能够追上慢指针,那就说明其中有一个环,否则不存在环。

       这个方法的时间复杂度为O(n),空间复杂度为O(1),实际使用两个指针。

原理


       链表存在环,则fast和slow两指针必然会在slow对链表完成一次遍历之前相遇,证明如下:
       slow首次在A点进入环路时,fast一定在环中的B点某处。设此时slow距链表头head长为x,B点距A点长度为y,环周长为s。因为fast和slow的步差为1,每次追上1个单位长度,所以slow前行距离为y的时候,恰好会被fast在M点追上。因为y<s,所以slow尚未完成一次遍历。

       fast和slow相遇了,可以肯定的是这两个指针肯定是在环上相遇的。此时,还是继续一快一慢,根据上面得到的规律,经过环长s,这两个指针第二次相遇。这样,我们可以得到环中一共有多少个节点,即为环的长度。

实现

#include <iostream>
using namespace std;

struct Node{
    int data;
    Node* next;
};

void Display(Node *head)// 打印链表
{
    if (head == NULL)
    {
        cout << "the list is empty" << endl;
        return;
    }
    else
    {
        Node *p = head;
        while (p)
        {
            cout << p->data << " ";
            p = p->next;
            if(p->data==head->data)//加个判断,如果环中元素打印完了就退出,否则会无限循环
                break;
        }
    }
    cout << endl;
}

bool IsExistLoop(Node* head)
{
    Node *slow = head, *fast = head;

    while ( fast && fast->next )
    {
        slow = slow->next;
        fast = fast->next->next;
        if ( slow == fast )
            break;
    }

    return !(fast == NULL || fast->next == NULL);
}

int GetLoopLength(Node* head)
{
    Node *slow = head, *fast = head;

    while ( fast && fast->next )
    {
        slow = slow->next;
        fast = fast->next->next;
        if ( slow == fast )//第一次相遇
            break;
    }
    slow = slow->next;
    fast = fast->next->next;
    int length = 1;       //环长度
    while ( fast != slow )//再次相遇
    {
        slow = slow->next;
        fast = fast->next->next;
        length ++;        //累加
    }
    return length;
}

Node* Init(int num) // 创建环形链表
{
    if (num <= 0)
        return NULL;
    Node* cur = NULL;
    Node* head = NULL;
    Node* node = (Node*)malloc(sizeof(Node));
    node->data = 1;
    head = cur = node;
    for (int i = 1; i < num; i++)
    {
        Node* node = (Node*)malloc(sizeof(Node));
        node->data = i + 1;
        cur->next = node;
        cur = node;
    }
    cur->next = head;//让最后一个元素的指针域指向头结点,形成环
    return head;
}

int main( )
{
    Node* list = NULL;
    list = Init(10);
    Display(list);

    if(IsExistLoop(list))
    {
        cout<<"this list has loop"<<endl;
        int length=GetLoopLength(list);
        cout<<"loop length: "<<length<<endl;
    }
    else
    {
        cout<<"this list do not has loop"<<endl;
    }

    system("pause");
    return 0;
}

输出结果



参考链接:https://blog.csdn.net/sdujava2011/article/details/39738313

猜你喜欢

转载自blog.csdn.net/caoshangpa/article/details/80363335