Skip to content

Commit 58593a9

Browse files
committed
day 3
1 parent 99be054 commit 58593a9

File tree

2 files changed

+61
-1
lines changed

2 files changed

+61
-1
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/*
2+
Linked List Cycle
3+
=================
4+
5+
Given head, the head of a linked list, determine if the linked list has a cycle in it.
6+
7+
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.
8+
9+
Return true if there is a cycle in the linked list. Otherwise, return false.
10+
11+
Example 1:
12+
Input: head = [3,2,0,-4], pos = 1
13+
Output: true
14+
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
15+
16+
Example 2:
17+
Input: head = [1,2], pos = 0
18+
Output: true
19+
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
20+
21+
Example 3:
22+
Input: head = [1], pos = -1
23+
Output: false
24+
Explanation: There is no cycle in the linked list.
25+
26+
Constraints:
27+
The number of the nodes in the list is in the range [0, 104].
28+
-105 <= Node.val <= 105
29+
pos is -1 or a valid index in the linked-list.
30+
31+
Follow up: Can you solve it using O(1) (i.e. constant) memory?
32+
*/
33+
34+
/**
35+
* Definition for singly-linked list.
36+
* struct ListNode {
37+
* int val;
38+
* ListNode *next;
39+
* ListNode(int x) : val(x), next(NULL) {}
40+
* };
41+
*/
42+
43+
class Solution
44+
{
45+
public:
46+
bool hasCycle(ListNode *head)
47+
{
48+
auto fast = head, slow = head;
49+
while (fast && fast->next)
50+
{
51+
fast = fast->next->next;
52+
slow = slow->next;
53+
if (fast == slow)
54+
return true;
55+
}
56+
return false;
57+
}
58+
};

Leetcode Daily Challenge/February-2021/README.MD

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,6 @@
22

33
| Day | Question Links | Solutions |
44
| :-: | :------------- | :-------: |
5-
| 1. | [Number of 1 Bits](https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/584/week-1-february-1st-february-7th/3625/) | [cpp](./01.%20Number%20of%201%20Bits.cpp) |
5+
| 1. | [Number of 1 Bits](https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/584/week-1-february-1st-february-7th/3625/) | [cpp](./01.%20Number%20of%201%20Bits.cpp) |
6+
| 2. | []() | [cpp](./02.%20.cpp) |
7+
| 3. | [Linked List Cycle](https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/584/week-1-february-1st-february-7th/3627/) | [cpp](./03.%20Linked%20List%20Cycle.cpp) |

0 commit comments

Comments
 (0)