您的位置:首页 > 编程语言 > Go语言

LeetCode -- LinkedListCycle

2014-07-14 22:12 218 查看
Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

/**

 * Definition for singly-linked list.

 * struct ListNode {

 *     int val;

 *     ListNode *next;

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

 * };

 */

用两个指针,一个每次前进1步,一个每次前进2步,如果存在环,那么两个指针就终会相遇。要注意判断快慢针前进过程中是否会是NULL。

class Solution{
public:
bool hasCycle(ListNode *head){

ListNode *pointer1 = head;
ListNode *pointer2 = head;

while(1){
if(pointer1 == NULL) return false;

pointer2 = pointer2 ->next;
if(pointer2 == NULL) return false;

pointer2 = pointer2 ->next;
if(pointer2 == NULL) return false;

if(pointer2 == pointer1)return true;

pointer1 = pointer1 ->next;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode algorithm