【leetcode】Linked List Cycle
2015-01-05 22:12
176 查看
问题描述:
思路:
1.遍历链表,比较set中是否包含节点的地址,如果包含说明是有环,如果不包含,则将地址存入到set中;
缺点:leetcdoe显示time limited
2.快慢指针:我很喜欢一个比喻,有两个人同时绕着操场跑,一个速度是另一个速度的两倍,这样以来两人肯定回碰到一起;快慢指针也是同理,在遍历时,让一个节点的后向遍历速度为next;另一个为next.next;如果有重复,两个指针肯定回碰到;
Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space?
思路:
1.遍历链表,比较set中是否包含节点的地址,如果包含说明是有环,如果不包含,则将地址存入到set中;
缺点:leetcdoe显示time limited
//time limited.. public boolean hasCycle1(ListNode head) { if(head==null) return false; Set<String> address = new HashSet<String>(); while(head.next!=null){ System.out.println(head.toString()); if(address.contains(head.toString())) break; address.add(head.toString()); head=head.next; } if(head.next==null) return false; return true; }
2.快慢指针:我很喜欢一个比喻,有两个人同时绕着操场跑,一个速度是另一个速度的两倍,这样以来两人肯定回碰到一起;快慢指针也是同理,在遍历时,让一个节点的后向遍历速度为next;另一个为next.next;如果有重复,两个指针肯定回碰到;
public boolean hasCycle(ListNode head) { boolean result = false; if(head==null) return false; ListNode flagA = head; ListNode flagB = head; while(flagB.next!=null&&flagB.next.next!=null){ flagA=flagA.next; flagB=flagB.next.next; if(flagA==flagB){ result = true; break; } } return result; }
相关文章推荐
- [LeetCode#142]Linked List Cycle II
- leetcode -- Linked List Cycle II
- leetcode-Linked List Cycle II 链表判环以及求环起始位置
- [LeetCode]Linked List Cycle II
- leetcode - Linked List Cycle II
- <leetcode系列> Linked List Cycle II
- [Leetcode]Linked List Cycle
- LeetCode——Linked List Cycle
- leetcode 141:Linked List Cycle 问题与解答
- LeetCode 学习 LinkedList 专项(5)—— Linked List Cycle
- [LeetCode] [快慢指针] Linked List Cycle
- LeetCode141:Given a linked list, determine if it has a cycle in it.
- leetcode笔记--Linked List Cycle II
- LeetCode——Linked List Cycle II
- LeetCode 141 Linked List Cycle(链表判环)
- leetcode_c++:链表:Linked List Cycle(141)
- leetcode 141-Linked List Cycle
- [LeetCode] - Linked List Cycle II
- [Leetcode-142] Linked List Cycle II(链表有环详细分析)
- Leetcode 141 Linked List Cycle