Description:Given a linked list, determine if it has a cycle in it.
Follow up: Can you solve it without using extra space?
题目:判断一个给定的列表,是否成环,也就是,判断是否首尾相连。
思路:创建一个快指针,一个慢指针。快指针一次走两布,慢指针一次走一步。慢指针走一圈,快指针走两圈,如果两个指针指向位置相同了,说明列表是环状的。
Language:c
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
struct ListNode *fast = (struct ListNode *)malloc(sizeof(struct ListNode));
struct ListNode *slow = (struct ListNode *)malloc(sizeof(struct ListNode));
fast = head;
slow = head;
while(fast != NULL && fast->next != NULL){
slow = slow->next;
fast = fast->next->next;
if(fast == slow){
return true;
}
}
return false;
}
Language : cpp
/**
* 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 *fast = head;
ListNode *slow = head;
while(fast != NULL && fast->next != NULL){
slow = slow->next;
fast = fast->next->next;
if(fast == slow){
return true;
}
}
return false;
}
};
Language: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
"""
try:
slow = head
fast = head.next
while slow is not fast:
slow = slow.next
fast = fast.next.next
return True
except:
return False
LeetCode题目汇总: https://github.com/Jack-Cherish/LeetCode