`
kmplayer
  • 浏览: 500674 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

找出带环单链表入口点

阅读更多
找出一个带环单链表的环开始的结点
一个n方复杂度的算法:

#include <iostream>
using namespace std;

//定义数据结构
struct Node
{
    Node(int i):data(i),next(0){}
    int data;
    Node* next;
};


//释放带环的节点
void node_circle_free(Node* node,Node* point)
{
    static bool flag=false;
    if(node->next!=point||!flag)
    {
        if(node->next==point)
            flag=true;
        node_circle_free(node->next,point);
    }
    delete node;
    return;
}

//打印链表中的数据,存在环,必定是死循环
void node_seq_print(Node* node,Node* point)
{
    if(node==NULL)
        return;
    static bool flag=false;
    cout<<node->data<<" ";
    if(node->next!=point||!flag)
    {
        if(node->next==point)
            flag=true;
        node_seq_print(node->next,point);
    }
    return;
}

//返回链表环的入口点
Node* returnCircleListPoint(Node* node)
{
    int cnt1=0;
    int cnt2=0;
    Node* p1=node;
    Node* p2=node;
    while(true)
    {
        p1=p1->next;
        cnt1++;
        while(p2!=p1)p2=p2->next,cnt2++;
        if(cnt2<cnt1)
            return p1;
        p2=node;
        cnt2=0;
    }
}

int main()
{
    Node *node=new Node(0);
    Node* head=node;
    Node* temp=0;
    for(int i=1;i<7;++i)
    {
        node->next=new Node(i);
        node=node->next;
        if(i==4) //设定环的入口
            temp=node;
        if(i==6) //这个设定为尾节点
        {
            assert(temp!=0);
            node->next=temp;
        }
    }
    Node* circlePoint=returnCircleListPoint(head);
    cout<<circlePoint->data<<endl;

    node_seq_print(head,circlePoint);
    node_circle_free(head,circlePoint);

    return 0;
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics