Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
給一linked list,判斷裡面有沒有cycle。
我們用一個整數pos去代表linked list的尾巴指回linked list前面的哪個位置,如果pos為-1,代表裡面沒有cycle。
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.
Learn More →
Example 2:
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Learn More →
Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
Learn More →
pos
就好,但是你當然拿不到這個變數。linked list
裡面有cycle
。null
的時候不能再跑向下一個。
/**
* 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) {
if(!head)return false;
ListNode* one=head->next;
ListNode* two=head->next;
if(!one)return false;
two = two->next;
if(!two)return false;
for(;one&&two;one=one->next,two=two->next)
{
two=two->next;
if(!two)return false;
if(one==two)return true;
}
return false;
}
};
LeetCode
C++
1. Two Sum
Nov 15, 2023You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions:
Nov 15, 2023Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7.
Nov 9, 2023There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network.
Nov 9, 2023or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up