• 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;
            
            
        }
    }
  • 相关阅读:
    后端开发-Mybatis开发之一
    Zeppelin推荐
    构建Maven项目
    linux使用curl进行WebService接口测试
    html和jsp的区别及优缺点
    Ajax实现Web长连接
    java生成二维码
    Android调用传感器和震动
    【Head First设计模式-读书笔记】装饰者模式
    【Head First设计模式-读书笔记】观察者模式
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6066233.html
Copyright © 2020-2023  润新知