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

LeetCode Linked List Cycle

时间:2015-03-06 15:51:34      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

1. 题目

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

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


2.解决方案


class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(!head){
		return false;
	}

	ListNode* slowPoint = head;
	ListNode* fastPoint = head;

	while(slowPoint->next){
		//slow point move one step
		slowPoint = slowPoint->next;
		//fast point move two step
		if(fastPoint->next){
			fastPoint = fastPoint->next;
		}else{
			return false;
		}
		if(fastPoint->next){
			fastPoint = fastPoint->next;
		}else{
			return false;
		}
		if(slowPoint->val == fastPoint->val){
			return true;
		}
	}
	return false;
    }
};

思路:用快慢指针来走,如果有环的话,一定会遇到一起。

http://www.waitingfy.com/archives/1591

LeetCode Linked List Cycle

标签:

原文地址:http://blog.csdn.net/fox64194167/article/details/44099379

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