zoukankan      html  css  js  c++  java
  • leetcode141

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public int val;
     *     public ListNode next;
     *     public ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution
        {
            public bool HasCycle(ListNode head)
            {
                //if (head == null)
                //{
                //    return false;
                //}
                //else
                //{
                //    var temp = head;
                //    while (head.next != null)
                //    {
                //        var cur = head.next;
                //        if (temp == cur)
                //        {
                //            return true;
                //        }
                //        else
                //        {
                //            head = head.next;
                //        }
                //    }
                //    return false;
                //}
    
                if (head == null) return false;
                ListNode walker = head;
                ListNode runner = head;
                while (runner.next != null && runner.next.next != null)
                {
                    walker = walker.next;
                    runner = runner.next.next;
                    if (walker == runner) return true;
                }
                return false;
            }
        }

    https://leetcode.com/problems/linked-list-cycle/#/description

    补充一个python的版本:

     1 class Solution:
     2     def hasCycle(self, head: ListNode) -> bool:
     3         if head == None:
     4             return False
     5         slow,fast = head,head
     6         while fast != None and fast.next != None:
     7             slow = slow.next
     8             fast = fast.next.next
     9             if slow == fast:
    10                 return True
    11         return False
  • 相关阅读:
    awk例子
    vsftp搭建
    makefile里PHONY的相关介绍
    youget帮助使用手册
    正则表达式全集
    常用的正则表达式
    基本用法
    心情
    asp.net和java
    java and asp.net
  • 原文地址:https://www.cnblogs.com/asenyang/p/6747011.html
Copyright © 2011-2022 走看看