题目表述如下:
下面提供两种解题思路:
第一种:(遍历思想)
#include<cstdio>
// 本题考查的是静态链表
int main() {
int list[1000]; // 存放链表指针(下标),这里没有必要保存链表里的数据
int visited[1000] = {0}; // 标志是否访问
int ind = 1;
int n, m;
while(scanf("%d%d", &m, &n)==2) {
list[ind++] = n;
if(n==-1) break;
}
int isLoop = 0;
for(int i=1; i!=-1; i=list[i]) {
if(visited[i]) { // 前面已经访问过了,表明有环
isLoop = 1; break;
}
visited[i] = true;
}
if(isLoop) printf("true\n");
else printf("false\n");
return 0;
}
第二种:
#include<iostream>
using namespace std;
struct List {
int num;
List *next;
};
bool isLoop() {
bool flag = false;
List *p = NULL, *q = NULL;
int m, n, count = 1;
cin >> m >> n;
p = new List;
p->num = m;//结点数据亦可不保存
while (n != -1) {
if ((n-count) == 1) {//直接后继结点
q = p;
p = p->next;
}else if ((n-count) == -1) {//前驱结点
q = p->next;
flag = true;
}else if ((n-count) == 0) {//指向当前结点
q = p;
flag = true;
}else {
break;
}
cin >> m >> n;
p = new List;
p->num = m;
count++;
}
p->next = NULL;
return flag;
}
int main() {
cout<<(isLoop()?"true":"false");
return 0;
}
问题扩展:
http://blog.csdn.net/thefutureisour/article/details/8174313