leetcode141: 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上鍊表的題都是沒有頭結點的,這點大家要記住。而且若連結串列有環,也是最後一個節點形成的環。
大家考慮這樣一個問題,連結串列的環相當於一個圓形操場。假設有兩個人在圓形操場上無限迴圈的跑,那麼速度快的一定能追得上速度慢的。同理,若要判斷一個連結串列是否有環,可設計快慢指標,當快慢指標都進入環的時候,若最終兩個指標相遇,必可說明連結串列存在環。下面就要考慮快慢指標的步長,從跑操場的情況來看,不管慢的有多慢,快得有多快,最終肯定能相遇。同理,連結串列中,也可隨意指定快慢指標的步長,無非就是跑的圈數多少的問題。
/**
* 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) {
ListNode p=head;//快指標
ListNode q=head;//慢指標
while(p!=null&&q!=null&&p.next!=null){//邊界條件是出現空指標,就返回false;
q=q.next;
p=p.next.next;//空指標沒有next,否則會出現NullPointerException問題
if(p==q)return true;
}
return false;
}
}
相關文章
- LeetCode141:Linked List CycleLeetCode
- leetcode Linked List CycleLeetCode
- Leetcode Linked List Cycle IILeetCode
- [leetcode]linked-list-cycle-iiLeetCode
- Leetcode-Linked List Cycle IILeetCode
- LeetCode | 141 linked list cycleLeetCode
- 【Leetcode】141. Linked List CycleLeetCode
- Leetcode 142. Linked List Cycle IILeetCode
- 【Leetcode】142.Linked List Cycle IILeetCode
- LeetCode142:Linked List Cycle IILeetCode
- Linked List Cycle leetcode java (連結串列檢測環)LeetCodeJava
- 資料結構與演算法 | Leetcode 141:Linked List Cycle資料結構演算法LeetCode
- Linked List Cycle leetcode II java (尋找連結串列環的入口)LeetCodeJava
- LeetCode 之 JavaScript 解答第141題 —— 環形連結串列 I(Linked List Cycle I)LeetCodeJavaScript
- 每天一道LeetCode--141.Linked List Cycle(連結串列環問題)LeetCode
- 92. Reverse Linked List II
- Leetcode Reverse Linked List IILeetCode
- [LintCode] Palindrome Linked List
- LeetCode Delete Node in a Linked ListLeetCodedelete
- Leetcode Palindrome Linked ListLeetCode
- LeetCode 382 Linked List Random NodeLeetCoderandom
- LeetCode-Palindrome Linked ListLeetCode
- LeetCode-Linked List Random NodeLeetCoderandom
- LeetCode-Odd Even Linked ListLeetCode
- Leetcode-Reverse Linked List IILeetCode
- leetcode刷題--Reverse Linked ListLeetCode
- Reverse Linked List II leetcode javaLeetCodeJava
- [LeetCode] 328. Odd Even Linked ListLeetCode
- 【LeetCode】Flatten Binary Tree to Linked ListLeetCode
- Leetcode Flatten Binary Tree to Linked ListLeetCode
- leetcode刷題--Remove Linked List ElementsLeetCodeREM
- LeetCode之Odd Even Linked List(Kotlin)LeetCodeKotlin
- LeetCode | 203. Remove Linked List ElementsLeetCodeREM
- Leetcode 234. Palindrome Linked ListLeetCode
- Leetcode 203. Remove Linked List ElementsLeetCodeREM
- Leetcode-Flatten Binary Tree to Linked ListLeetCode
- Flatten Binary Tree to Linked List leetcode javaLeetCodeJava
- [LeetCode] 2487. Remove Nodes From Linked ListLeetCodeREM