判断链表是否有环,入口节点以及环的大小(C++)

这篇博客对上述问题有详细的解释:判断链表中是否有环 ----- 有关单链表中环的问题

这里只做C++的一个代码实现,主要包含构建环形链表,判断是否有环以及环的大小。

#include<iostream>
#include<vector>

using  namespace std;

struct Node {
	int val;
	Node* next;
	Node(int num):val(num),next(nullptr){}
};

Node* CreatCircularList() {
	Node* head = new Node(0);
	Node* ptr = head, *enterNode = nullptr;
	cout << "Please input a number(0 to entry node, q to quit): ";
	int temp;
	bool sign = false;
	while (cin >> temp) {
		Node* newNode = new Node(temp);
		if (!sign&&temp == 0) {
			enterNode = newNode;
			sign = true;
		}
		newNode->next = ptr->next;
		ptr->next = newNode;
		ptr = newNode;
		cout << "Please input a number(0 to entry node, q to quit): ";
	}
	if(sign) ptr->next = enterNode;
	return head->next;
}

bool IsLoop(Node* head) {
	if (head == nullptr || head->next == nullptr) return false;
	Node* low = head->next;
	Node* fast = head->next->next;
	while (fast != nullptr && fast->next != nullptr && fast != low) {
		fast = fast->next->next;
		low = low->next;
	}
	if (fast == low) return true;
	else return false;
}

Node* findEnterVal(Node* head) {
	if (head == nullptr || head->next == nullptr) return nullptr;
	Node* low = head->next;
	Node* fast = head->next->next;
	while (fast != nullptr && fast->next != nullptr && fast != low) {
		fast = fast->next->next;
		low = low->next;
	}
	if (fast == low) {
		low = head;
		while (low != fast) {
			low = low->next;
			fast = fast->next;
		}
		return low;
	}
	else return nullptr;
}

int LoopLength(Node* head) {
	if (!IsLoop(head)) return 0;
	Node* enterNode = findEnterVal(head);
	Node* ptr = enterNode->next;
	int count = 1;
	while (ptr != enterNode) {
		count++;
		ptr = ptr->next;
	}
	return count;
}

int main() {
	Node* head = CreatCircularList();
	cout << "#1 If there is a cycle in it: " << IsLoop(head) << endl;
	Node* temp = findEnterVal(head);
	if (temp != nullptr)
		cout << "#2 Enter node value: " << findEnterVal(head)->val << endl;
	else
		cout << "#2 List is not a cycle!" << endl;
	cout << "#3 Loop length: " << LoopLength(head) << endl;
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值