zoukankan      html  css  js  c++  java
  • LeetCode(141): 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?

    题意:判断一个链表中是否存在环。

    思路:(参考别人的做法)采用“快慢指针”检查链表是否含有环。即让一个指针一次走一步,另一个指针一次走两步,如果链表中含有环,快的指针会再次和慢的指针相遇。

    代码:

    public boolean hasCycle(ListNode head) {
            ListNode slow = head;
            ListNode fast = head;
            while(fast!=null&&fast.next!=null){
                slow = slow.next;
                fast = fast.next.next;
                if(slow==fast)
                return true;
            }
            return false;
        }
  • 相关阅读:
    奔溃瞬间1
    面试知识点blog汇总
    贪心
    树 和 图
    DFS 和 BFS
    STL
    哈希表
    手写堆
    并查集
    二项式反演学习笔记
  • 原文地址:https://www.cnblogs.com/Lewisr/p/5134493.html
Copyright © 2011-2022 走看看