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;
            
            
        }
    }
  • 相关阅读:
    对软件工程的理解及问题
    使用Junit等工具进行单元测试
    软件工程
    进销存管理系统——可行性分析
    使用Junit等工具进行单元测试
    两个人的分组
    物联网软件工程 认识与问题
    二人项目
    使用Junit等工具进行单元测试
    软件工程
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6066233.html
Copyright © 2011-2022 走看看