Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Special case handling #60

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions chapter-2-Linked-Lists/2-8-loop-detection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,23 @@ void removeLoop( Node * loopNode, Node * head )
{
Node * ptr1 = head;
Node * ptr2 = loopNode;
while ( ptr1->next != ptr2->next ) {
ptr1 = ptr1->next;
ptr2 = ptr2->next;

//In case of full cycle, should move to the final node and terminate the loop from there.
//Otherwise, the head node will be seperated from the rest of the list
if (loopNode == head)
{
while (ptr2->next != head) {
ptr2 = ptr2->next;
}
}
else
{
while (ptr1->next != ptr2->next) {
ptr1 = ptr1->next;
ptr2 = ptr2->next;
}
}

//ptr2 has reached start of loop, now removing the loop.
ptr2->next = nullptr;
}
Expand Down Expand Up @@ -83,6 +96,10 @@ int main()
printList( head );
std::cout << "Inserting loop, connecting 5 to 2 \n";
head->next->next->next->next->next = head->next;
// to test the special case, replace the loop with
// std::cout << "Inserting loop, connecting 5 to 1 \n";
// head->next->next->next->next->next = head;

std::cout << "Detecting and deleting loop\n";
detectAndRemoveCycle(head);
std::cout << "Back to the same old list\n";
Expand Down