`
阿尔萨斯
  • 浏览: 4109635 次
社区版块
存档分类
最新评论

数据结构 - 判断一个链表是否有循环(C++)

 
阅读更多
#include <iostream>

#define NULL 0

using namespace std;

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

Node* create()
{
	Node* head = NULL;
	Node* rear = head;
	Node* p; // The pointer points to new created node.
	char tmp;

	do
	{
		cout << "Please input integer or char '#':";
		cin >> tmp;
		if(tmp != '#')
		{
			p = new Node;
			p->data = tmp;
			p->next = NULL;

			if(head == NULL)
			{
				head = p;
			}
			else
			{
				rear->next = p;
			}
			rear = p;
		}
	}
	while(tmp != '#');

	return head;
}

void print(Node* head)
{
	cout << "The current list is: ";
	Node* p = head;
	if(head != NULL)
	{
		do
		{
			cout << p->data << cout << ' ';
			p = p->next;
		}
		while(p != NULL);
	}
	cout << "\r\n";
}

int isLoop(Node* l)
{
	if(!l)
	{
		return 0;
	}
	Node* p = l->next;
	while(p != l && p != NULL)
	{
		p = p->next;
	}
	if(p == NULL)
	{
		return 0;
	}
	else
	{
		return 1;
	}
}

int main()
{
	Node* list = create();
	print(list);
	int i = isLoop(list);
	cout << i << endl;
	system("pause");
	return 0;
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics