zoukankan      html  css  js  c++  java
  • 【LeetCode】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?

    解答

    首先要注意空链表不成环;不能开额外的空间,即空间复杂度是o(1),可採用“快慢指针”查检查链表是否含有环,假设在快的指针可以追上慢的指针,则有环。否则无环。

    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public boolean hasCycle(ListNode head) {
            if(head==null){
                return false;
            }
            ListNode fast=head;
            ListNode slow=head;
            while(fast!=null&&fast.next!=null){  //仅仅要推断快指针是否为空就能够了,可是注意当fast是为结点时,fast.next为空。若推断fast.next.next则会报NullPointerException
                slow=slow.next;
                fast=fast.next.next;
                if(slow==fast){
                    return true;
                }
            }
            return false;
        }
    }


    ---EOF---

    版权声明:本文博客原创文章。博客,未经同意,不得转载。

  • 相关阅读:
    PHP开发APP接口(九)
    C#深入理解类型
    C#从委托、lambda表达式到linq总结
    C# ==和Equals()
    C# 泛型
    C# Reflection
    原声JS网络请求
    JavaScript预编译
    泛型初探
    C#内存分配
  • 原文地址:https://www.cnblogs.com/yxwkf/p/4690737.html
Copyright © 2011-2022 走看看