首页 > 代码库 > Linked List Cycle [leetcode]

Linked List Cycle [leetcode]

#include<iostream>
#include<string>
#include<fstream>
using namespace std;

 struct ListNode {
     int val;
     ListNode *next;
     ListNode(int x) : val(x), next(NULL) {}
 };

class Solution {
public:
	bool hasCycle(ListNode *head) {
		ListNode* fast_walker = head;
		ListNode* slow_walker = head;
		while (fast_walker && slow_walker){
			fast_walker = fast_walker->next;
			if (fast_walker) fast_walker = fast_walker->next;
			else break;
			slow_walker = slow_walker->next;
			if (slow_walker == fast_walker){
				return true;
			}
		}
		return false;
	}
};

/* 从命令行接受数据 初始化 链表
int main(){
	ListNode* head = NULL;
	ListNode* tmp = head;
	int in = 0;
	while (cin >> in){
		tmp->next = new ListNode(in);
		tmp = tmp->next;
		tmp->next = NULL;
	}
	Solution ss;
	ss.hasCycle(head);

	return 0;
}
*/
//从文本文件中初始化链表
int main(){
	fstream fin("test.txt");
	ListNode* head(0);//此时并没有分配存储地址
	ListNode* tmp = head;//此时相当于 tmp = NULL
	int in = 0;
	while (fin >> in){
		if (!head) {
			head = new ListNode(in);
			tmp = head;
		}
		else{
			while (tmp->next != NULL) tmp = tmp->next;
			tmp->next = new ListNode(in);
			tmp = tmp->next;
			tmp->next = NULL;
		}
	}
	//制造一个环
	tmp->next = head->next;
	Solution ss;
	bool retult = ss.hasCycle(head);
	system("pause");
	return 0;
}


Linked List Cycle [leetcode]