1. 程式人生 > >leetcode141 Linked List Cycle(判斷連結串列是否有環)

leetcode141 Linked List Cycle(判斷連結串列是否有環)

題目要求 (高頻題)

給一個連結串列,判斷是否有環存在。為了表示連結串列中的環,我們用一個整數pos來表示環的位置,如果pos等於-1,則表示沒有環。

示例

**Example 1**
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.

在這裡插入圖片描述

**Example 2**
Input: head = [1], pos = -1
Output: false
Explanation:
There is no cycle in the linked list.

在這裡插入圖片描述

解題思路

快慢指標

判斷連結串列中是否存在環是一類非常易考的題目,它通過“快慢”指標的技巧能夠在短時間內找到連結串列中是否存在環。既簡單又高效,只要判斷快指標是否和慢指標相遇即可。

主要程式碼 c++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution { public: bool hasCycle(ListNode *head) { ListNode *slow = head; ListNode *fast = head; while(fast && fast->next) // 判斷為空的情況 { slow = slow->next; fast = fast->next->next; //快指標每次走兩步 if(slow==fast)
return true; // 若快慢指標相遇 則有環 } return false; //說明沒環直接到末尾null,有環進while裡 } };

相似題目

leetcode876. Middle of the Linked List(尋找連結串列的中間元素)

原題連結:https://leetcode.com/problems/linked-list-cycle/