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

```/**
* struct ListNode {
*     int val;
*     struct ListNode *next;
* };
*/
struct ListNode *fast = (struct ListNode *)malloc(sizeof(struct ListNode));
struct ListNode *slow = (struct ListNode *)malloc(sizeof(struct ListNode));
while(fast != NULL && fast->next != NULL){
slow = slow->next;
fast = fast->next->next;
if(fast == slow){
return true;
}
}
return false;
}```

Language : cpp

```/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
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):
"""
:rtype: bool
"""
try:
while slow is not fast:
slow = slow.next
fast = fast.next.next
return True
except:
return False```

LeetCode题目汇总： https://github.com/Jack-Cherish/LeetCode

82 篇文章38 人订阅

0 条评论

## 相关文章

You are given two non-empty linked lists representing two non-negative integers....

791

### LeetCode 2 & 455 Add Two Numbers I&II

You are given two non-empty linked lists representing two non-negative integers....

770

### Leetcode 86 Partition List

Given a linked list and a value x, partition it such that all nodes less than x...

1876

842

### Leetcode 141 Linked List Cycle

Given a linked list, determine if it has a cycle in it. Follow up: Can you so...

1839

912

### 83. Remove Duplicates from Sorted List(Linked List-Easy)

Given a sorted linked list, delete all duplicates such that each element appear ...

1867

632

### 链表逆序

1.构造5个节点a,b,c,d,e,并对它们进行初始化； 2.将a,b,c,d,e,5个节点连接在一起

904

### Leetcode 21 Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should b...

1999