zoukankan      html  css  js  c++  java
  • leetcode 141. 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?

    题意:

          判断一个链表是否有环。

    解决方案:

          双指针,快指针每次走两步,慢指针每次走一步,

                如果有环,快指针和慢指针会在环内相遇,fast == slow,这时候返回true。

                如果没有环,返回false.

    /**
     * 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) {
            ListNode fast = head, slow = head;
            if(head == null || head.next == null) return false;
            
            while(fast != null && fast.next != null){
                fast = fast.next.next;
                slow = slow.next;
                
                if(fast == slow){
                    return true;
                }
            }
            
            return false;
        }
    }
  • 相关阅读:
    2016.6.26考试
    爆搜。。。。。。。
    9.18目标
    9.17水题总结
    9.16测试
    9.10考试
    jzoj P1163 生日派对灯
    9.04考试总结
    8/8刷题记录
    a[i++]
  • 原文地址:https://www.cnblogs.com/iwangzheng/p/5695174.html
Copyright © 2011-2022 走看看