LeetCode 141. Linked List Cycle

141. 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?

就是找链表是否有环,挺标准的算法,看了看leetcode解法还蛮多的

最简单想到的是用HashSet

public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head==null)
            return false;
        Set<ListNode> set = new HashSet<>();
        ListNode cur = head.next;
        while(cur!=null){
            if(set.contains(cur)){
                return true;
            }else{
                set.add(cur);
                cur=cur.next;
            }
            
        }
        return false;
        
    }
}

不适用任何extra space的话,还是蛮有难度的

第一种:破坏标记

将每一个遍历过的结点都做一个标记:将其指向头结点,那么如果遍历到一个结点指向头节点,说明有环

这个做法虽然是做到了只用constant space,但是会破坏原有链表,不算是好办法

public boolean hasCycle2(ListNode head) {
	if(head == null || head.next == null) {
		return false;
	}
	ListNode node = head;
	while(node != null) {
		if(node.next == head) {
			return true;
		}
		ListNode temp = node.next;
		node.next = head;
		node = temp;
	}
	return false;
}

第二种:双指针快慢遍历(Floyd cycle detection algorithm)

用两个不同速度的指针来遍历链表,如果有环,那么这2个指针必定相遇

public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null) return false;
        
        ListNode slow = head;
        ListNode fast = head;
        
        while (fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            
            if (fast == null) return false;
            if (slow == fast || slow == fast.next) return true;
        }
        
        return false;
    }
}

 

转载于:https://my.oschina.net/u/2486965/blog/754676

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值