您的位置:首页 > 其它

判断单链表是否带环(某公司实习生招聘笔试试题)

2012-10-19 20:29 295 查看
#include<iostream>
using namespace std;

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

Node *createList(int n)
{
Node *p = new Node
;
for( int i = 1; i < n; ++i)
{
p[i - 1].next = &p[i];
p[i - 1].data = i;
}
p[n - 1].next = NULL;
p[n - 1].data = n;
return p;
}

Node *createListWithRing(int n)
{
Node *p = new Node
;
for( int i = 1; i < n; ++i)
{
p[i - 1].next = &p[i];
p[i - 1].data = i;
}
p[n - 1].next = &p[n/2];
p[n - 1].data = n;
return p;
}

//pFast相当于摩托车,pSlow相当于自行车
//摩托车在前,自行车在后,如果还能相遇,则必然有环
bool listHasRing(Node *p)
{
Node *pSlow = &p[0];
Node *pFast = &p[1];
while(NULL != pSlow && NULL != pFast -> next)
{
if(pSlow == pFast)
return true;
pSlow = pSlow -> next;
pFast = pFast -> next ->next;
}
return false;
}

void print(bool b)
{
if(b)
cout << "There is a ring in the list." << endl;
else
cout << "There is no ring in the list." << endl;
}

int main()
{
int n = 10;
Node *head = createList(n);
print(listHasRing(head));
delete [] head;

head = createListWithRing(10);
print(listHasRing(head));
delete [] head;
return 0;
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐