首页 > 其他 > 详细

Linked List Cycle [leetcode]

时间:2014-08-31 23:04:12      阅读:330      评论:0      收藏:0      [点我收藏+]
#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]

原文:http://blog.csdn.net/u011409995/article/details/38964109

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!