forked from srishilesh/Data-Structure-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path141_Linked_list_cycle
52 lines (43 loc) · 1.35 KB
/
141_Linked_list_cycle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# https://leetcode.com/problems/linked-list-cycle/
# FLOYD TORTOISE AND HARE APPROACH
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
try:
slow = head
fast = head.next
while(slow is not fast):
slow = slow.next
fast = fast.next.next
return True
except:
return False
# if(head == None or head.next==None):
# return False
# temp = head
# temp1 = head
# while(temp!=None):
# temp1 = temp.next
# while(temp1!=None):
# if(temp.next==temp1.next):
# return True
# temp1 = temp1.next
# temp = temp.next
# return False
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if (head == None or head.next == None):
return False
slow = fast = head
fast = fast.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if (slow == fast):
return True
return False
# https://leetcode.com/problems/linked-list-cycle/solution/