zoukankan      html  css  js  c++  java
  • [LeetCode]Linked List Cycle

    题目:给定一个单链表,推断链表是否存在环路(是否能不使用额外内存空间)

    算法:快慢指针

    原理:每次,快指针走一步,慢指针走两步,若链表存在循环。则快慢指针终于必然会在某个节点汇合。否则直到遍历完整个链表都不会汇合

    /**
     * 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 (null==head || null==head.next) {
    	    		return false;
    	    	}
    	    	
    	    	ListNode fast = head;  // fast pointer take one step
    	    	ListNode slow = head.next.next;  // slow pointer take two steps
    	    	while (null!=fast && null!=slow) {
    	    		if (fast == slow) {
    	    			// fast pointer meet slow pointer, it means list has cycle!
    	    			return true;
    	    		}
    	    		
    	    		if (null == slow.next) {
    	    			// it mean slow pointer has reach the list tail! No cycle!
    	    			return false;
    	    		}
    	    		else {
    	    			fast = fast.next;
    		    		slow = slow.next.next;
    	    		}
    	    	}
    	    	return false;
    	    }
    }


  • 相关阅读:
    《算法竞赛进阶指南》0x42树状数组 楼兰图腾
    《算法竞赛进阶指南》0x41并查集 奇偶游戏
    .NET技术-常规操作
    TFS-在windows上配置自动化部署
    * 常用软件下载
    Docker 修改网桥网段
    Docker
    Docker
    NETCORE
    .NET框架
  • 原文地址:https://www.cnblogs.com/blfshiye/p/5416626.html
Copyright © 2011-2022 走看看