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

    /**
     * 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) {
            boolean hasCycle = true;
    		if(head == null)
    			hasCycle = false;
    		else{
    			ListNode first = head;
    			ListNode second = head;
    			do{
    				if(second.next == null || second.next.next == null){
    					hasCycle = false;
    					break;
    				}	
    				else{
    					first = first.next;
    					second = second.next;
    					second = second.next;
    				}
    			}while(first != second);
    		}
    		return hasCycle;
        }
    }
    

    The same method as above

    /**
     * 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) {
           boolean hasCycle = false;
            if(head != null){
                ListNode speedOne = head, speedTwo = head;
                while(!hasCycle){
                    if(speedTwo == null || speedTwo.next == null)
                        break;
                    else{
                        speedTwo = speedTwo.next.next;
                        speedOne = speedOne.next;
                        hasCycle = (speedOne == speedTwo)? true : false;
                    }
                }
            }
            return hasCycle;
        }
    }
    

      

  • 相关阅读:
    通过char与varchar的区别,学习可变长的字符类型
    laravel向视图传递变量
    MySQL数据库几种常用的索引类型使用介绍
    Java小知识点总结01
    好的代码习惯
    刻意练习
    算法
    经常复习
    kibana查询语法 使用教程
    工作思考
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3545282.html
Copyright © 2011-2022 走看看