mirror of
https://github.com/20kaushik02/leetcode-gulag.git
synced 2026-01-25 07:34:05 +00:00
day 33: 200-number-of-islands, 141-linked-list-cycle
This commit is contained in:
16
141-linked-list-cycle/driver.cpp
Normal file
16
141-linked-list-cycle/driver.cpp
Normal file
@@ -0,0 +1,16 @@
|
||||
#include "soln.hpp"
|
||||
|
||||
int main()
|
||||
{
|
||||
ListNode n5 = ListNode(5);
|
||||
ListNode n4 = ListNode(4, &n5);
|
||||
ListNode n3 = ListNode(3, &n4);
|
||||
ListNode n2 = ListNode(2, &n3);
|
||||
ListNode n1 = ListNode(1, &n2);
|
||||
n5.next = &n3;
|
||||
bool answer = true;
|
||||
|
||||
Solution soln;
|
||||
cout << "Checked cycle correctly? " << soln.test(&n1, answer) << endl;
|
||||
return 0;
|
||||
}
|
||||
19
141-linked-list-cycle/soln.cpp
Normal file
19
141-linked-list-cycle/soln.cpp
Normal file
@@ -0,0 +1,19 @@
|
||||
#include "soln.hpp"
|
||||
|
||||
bool Solution::hasCycle(ListNode *head)
|
||||
{
|
||||
ListNode *slow = head, *fast = head;
|
||||
while (fast && fast->next)
|
||||
{
|
||||
slow = slow->next;
|
||||
fast = fast->next->next;
|
||||
if (slow == fast)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool Solution::test(ListNode *head, bool answer)
|
||||
{
|
||||
return hasCycle(head) == answer;
|
||||
}
|
||||
18
141-linked-list-cycle/soln.hpp
Normal file
18
141-linked-list-cycle/soln.hpp
Normal file
@@ -0,0 +1,18 @@
|
||||
#include <bits/stdc++.h>
|
||||
using namespace std;
|
||||
/* Singly linked list*/
|
||||
struct ListNode
|
||||
{
|
||||
int val;
|
||||
ListNode *next;
|
||||
ListNode() : val(0), next(nullptr) {}
|
||||
ListNode(int x) : val(x), next(nullptr) {}
|
||||
ListNode(int x, ListNode *next) : val(x), next(next) {}
|
||||
};
|
||||
|
||||
class Solution
|
||||
{
|
||||
public:
|
||||
bool hasCycle(ListNode *head);
|
||||
bool test(ListNode *head, bool answer);
|
||||
};
|
||||
Reference in New Issue
Block a user