zoukankan      html  css  js  c++  java
  • LeetCode--141--环形链表

    问题描述:

    给定一个链表,判断链表中是否有环。

    思路:用快的指针追慢的指针,只要有圈,一定能追上。

    错误:

     1 class Solution(object):
     2     def hasCycle(self, head):
     3         """
     4         :type head: ListNode
     5         :rtype: bool
     6         """
     7         if head == None or head.next == None:
     8             return False
     9         p = head.next
    10         q = head.next.next
    11         while p and q:
    12             if p == q:
    13                 return True
    14             p = p.next
    15             if q.next != None:
    16                 q = q.next.next
    17         return False

    改正:

     1 class Solution(object):
     2     def hasCycle(self, head):
     3         """
     4         :type head: ListNode
     5         :rtype: bool
     6         """
     7         if head == None or head.next == None:
     8             return False
     9         p = head.next
    10         q = head.next.next
    11         while q and q.next:
    12             if p == q:
    13                 return True
    14             p = p.next
    15             q = q.next.next
    16         return False

    2018-09-12 21:03:17

  • 相关阅读:
    双端队列
    顺序循环队列
    顺序队列
    Counting Triangles(hd1396)
    蒟蒻之栈模拟递归
    链栈以及顺序栈应用—算数表达式
    栈的简单应用-进制转换
    链栈
    共享栈
    顺序栈
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/9637364.html
Copyright © 2011-2022 走看看