刷题记录第二十六天-环形链表

#include
using namespace std;
struct ListNode{
	int val;
	ListNode* next;
	ListNode(int x):val(x),next(nullptr){}
};
int main(){
	ListNode* node1 = new ListNode(1);
	ListNode* node2 = new ListNode(2);
	ListNode* node3 = new ListNode(3);
	ListNode* node4 = new ListNode(4);
	ListNode* node5 = new ListNode(5);
	node1->next = node2;
	node2->next = node3;
	node3->next = node4;
	node4->next = node5;
//	node5->next = node3;
	ListNode* slow = node1;
	ListNode* fast = node1;
	int flag=0;
	while(fast!=nullptr&&fast->next!=nullptr){
		slow = slow->next;
		fast = fast->next->next;
		if(slow==fast){
			flag=1;
			break;
		}
	}
	if(flag==0)cout<<"no cycle"<<" ";
	else cout<<"detect cycle"<<" ";
	system("pause");
}

你可能感兴趣的:(每日一题,链表,算法,数据结构)