Skip to content

Commit

Permalink
Prevent is_circular from infinite loop (#179)
Browse files Browse the repository at this point in the history
This commit refines the is_circular() to use slow and fast pointers
instead of a single pointer iteration. The original approach struggled
to detect mid-list loops without extra storage. The new method
effectively identifies such loops, albeit with a minor increase in
conditional checks, but without requiring additional storage.
  • Loading branch information
wilson20010327 authored Apr 1, 2024
1 parent 297bb61 commit 9bda828
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 deletions qtest.c
Original file line number Diff line number Diff line change
Expand Up @@ -875,17 +875,23 @@ static bool do_merge(int argc, char *argv[])
static bool is_circular()
{
struct list_head *cur = current->q->next;
struct list_head *fast = (cur) ? cur->next : NULL;
while (cur != current->q) {
if (!cur)
if (!cur || !fast || !fast->next)
return false;
if (cur == fast)
return false;
cur = cur->next;
fast = fast->next->next;
}

cur = current->q->prev;
fast = (cur) ? cur->prev : NULL;
while (cur != current->q) {
if (!cur)
if (!cur || !fast || !fast->prev)
return false;
cur = cur->prev;
fast = fast->prev->prev;
}
return true;
}
Expand Down

0 comments on commit 9bda828

Please sign in to comment.