1、题目:给定一个链表,判断它是否是循环链表
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
2、解答:该题目是链表是单链表,只有一个指针,所以循环一定在表尾,不存在循环后面还有结点。因此解法是 让一个结点每次走2步,另外一个结点走一步,若是循环链表,必定有相遇的时候。
3、C++代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *curr = head;
ListNode *currTwoStep = head;
if(!curr|| !curr->next)
return false;
currTwoStep = curr->next;
while(curr && currTwoStep){
if(curr == currTwoStep) //快的结点,遇到了走的慢的结点
return true;
if(!currTwoStep->next)
return false;
currTwoStep = currTwoStep->next->next; //快的结点走2步,慢的结点走1步
curr = curr->next;
}
return false;
}
};
python 代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
slow,fast = head,head
while fast and fast.next:
slow,fast = slow.next,fast.next.next
if slow is fast:
return True
return False