linked-list-cycle 1.0.0
Linked List Cycle
Loading...
Searching...
No Matches
Solution Class Reference

Public Member Functions

bool has_cycle_2 (ListNode *head)
 Check if the list has a cycle using set<ListNode*>
 
bool hasCycle (ListNode *head)
 Check if the list has a cycle using fast and slow pointers.
 

Detailed Description

Definition at line 68 of file main.cpp.

Member Function Documentation

◆ has_cycle_2()

bool Solution::has_cycle_2 ( ListNode head)
inline

Check if the list has a cycle using set<ListNode*>

Definition at line 74 of file main.cpp.

75 {
76 ListNode* current = head;
77 set<ListNode*> visited;
78 while (current != NULL)
79 {
80 if (visited.find(current) != visited.end())
81 return true;
82 visited.insert(current);
83 current = current->next;
84 }
85 return false;
86 }
Definition for singly-linked list.
Definition main.cpp:9
ListNode * next
Definition main.cpp:11

References ListNode::next.

◆ hasCycle()

bool Solution::hasCycle ( ListNode head)
inline

Check if the list has a cycle using fast and slow pointers.

Definition at line 91 of file main.cpp.

92 {
93 ListNode* fast = head;
94 ListNode* slow = head;
95 while (fast != NULL)
96 {
97 slow = slow->next;
98
99 fast = fast->next;
100 if (fast == NULL)
101 return false;
102
103 fast = fast->next;
104
105 if (slow == fast)
106 return true;
107 }
108 return false;
109 }

References ListNode::next.

Referenced by main().


The documentation for this class was generated from the following file: