Linked List Cycle
https://leetcode.com/problems/linked-list-cycle/
Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
题目:判断链表中是否存在环路。
来自南郭子綦解题思路:快慢指针技巧,slow指针和fast指针开始同时指向头结点head,fast每次走两步,slow每次走一步。如果链表不存在环,那么fast或者fast.next会先到None。如果链表中存在环路,则由于fast指针移动的速度是slow指针移动速度的两倍,所以在进入环路以后,两个指针迟早会相遇,如果在某一时刻slow==fast,说明链表存在环路。
1 # Definition for singly-linked list.
2 # class ListNode:
3 # def __init__(self, x):
4 # self.val = x
5 # self.next = None
6
7 class Solution:
8 # @param head, a ListNode
9 # @return a boolean
10 def hasCycle(self, head):
11 if head==None or head.next==None:
12 return False
13 fast=slow=head
14 while fast and fast.next:
15 slow=slow.next
16 fast=fast.next.next
17 if fast==slow:
18 return True
19 return False