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 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

你可能感兴趣的:(数据结构与算法)