码迷,mamicode.com
首页 > 其他好文 > 详细

141.Linked List Cycle

时间:2015-01-30 22:54:42      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

HideTags

 Linked List Two Pointers


#pragma once
#include<iostream>
using namespace std;

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


bool hasCycle(ListNode *head) {
	ListNode* p1 = head;
	ListNode* p2 = head;
	while (p1&&p2)
	{
		p1 = p1->next;
		p2 = p2->next;
		if (p2)
			p2 = p2->next;
		else
			return false;//到头,一定无环
		if (p1 == p2)
			return true;
	}
	return false;
}

void main()
{
	ListNode* l1 = new ListNode(1);
	ListNode* l2 = new ListNode(2);
	ListNode* l3 = new ListNode(3);
	ListNode* l4 = new ListNode(4);
	ListNode* l5 = new ListNode(4);
	l1->next = l2;
	l2->next = l3;
	//l3->next = l1;
	l4->next = l1;
	cout << hasCycle(l1) << endl;
	/*cout << hasCycle(l2) << endl;
	cout << hasCycle(l3) << endl;
	cout << hasCycle(l4) << endl;
	cout << hasCycle(l5) << endl;
	cout << hasCycle(l5->next) << endl;*/
	system("pause");

}


141.Linked List Cycle

标签:

原文地址:http://blog.csdn.net/hgqqtql/article/details/43308233

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!