LeetCode 141. Linked List Cycle
2016-10-06 00:00
281 查看
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; } }
相关文章推荐
- [Leetcode 36] 119 Pascal's Triangle II
- LeetCode Wildcard Matching 优化动态规划法和迭代算法
- [LeetCode]Climbing Stairs
- [LeetCode] Word Break
- Insertion Sort List 【leetcode】
- LeetCode | Best Time to Buy and Sell Stock
- LeetCode:Pascal's Triangle II
- [LeetCode]199.Binary Tree Right Side View
- [LeetCode]Anagrams
- leetcode116 Populating Next Right Pointers in Each Node
- leetcode 201: Bitwise AND of Numbers Range
- leetcode Find Minimum in Rotated Sorted Array(需要复习)
- leetcode -- Find Peak Element -- 找波峰--重点
- 111. Minimum Depth of Binary Tree LeetCode
- LeetCode-24.Swap Nodes in Pairs
- LeetCode 5. Longest Palindromic Substring
- 【leetcode】155. Min Stack
- LeetCode-Palindrome Permutation II
- LeetCode-Third Maximum Number
- 【leetcode】81. Search in Rotated Sorted Array II【java】