zoukankan      html  css  js  c++  java
  • leetcode 141. Linked List Cycle ----- java

    Given a linked list, determine if it has a cycle in it.

    Follow up:
    Can you solve it without using extra space?

    判断是否成环

    1、利用set,很简单,但是题目中说不要用额外的空间。

    /**
     * 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) {
            
            Set<ListNode> set = new HashSet<ListNode>();
    
            while( head != null ){
                if( set.contains(head) )
                    return true;
                set.add(head);
                head = head.next;
            }
            return false;
            
            
        }
    }

    2、设置两个指针,一个每次走两个,一个每次走一个,如果走到头,那么返回false,如果相同,那么返回true。

    /**
     * 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 || head.next == null )
                return false;
            ListNode fast = head.next;
            ListNode slow = head;
    
            while( fast.next != null && fast.next.next != null ){
                slow = slow.next;
                fast = fast.next.next;
                if( fast == slow )
                    return true;
            }
    
            return false;
            
            
        }
    }
  • 相关阅读:
    软件工程——小学生的四则运算(java)
    软件工程——小学生的四则运算
    利用python实现微信小项目
    SQLite3数据库
    爬虫———python
    模拟足球训练
    文件的转换
    学习成绩雷达图
    <dvi>
    vue 锚点跳转防止路径变化后,刷新页面报错的问题
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6066233.html
Copyright © 2011-2022 走看看