Skip to content

Commit bec2a7b

Browse files
committed
Implement q_delete_mid
Previously, q_delete_mid simply returned true without performing any deletion. This change implements the actual logic to find and remove the middle node from a doubly circular linked list. Instead of using the traditional slow-fast pointer approach, this implementation adopts a two-pointer convergence strategy, where pointers move inward from both ends simultaneously. This reduces the number of steps compared to the slow-fast pointer method, improving efficiency. Specifically, for a list of size n, this approach decreases the number of traversals by approximately n/2 steps. Change-Id: Ie9d2eadd23600f2999267151ed5c9468ffebf208
1 parent ddb885b commit bec2a7b

File tree

1 file changed

+10
-0
lines changed

1 file changed

+10
-0
lines changed

queue.c

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,16 @@ int q_size(struct list_head *head)
111111
bool q_delete_mid(struct list_head *head)
112112
{
113113
// https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/
114+
if (!head || list_empty(head))
115+
return false;
116+
struct list_head *access_next = head->next;
117+
struct list_head *access_prev = head->prev;
118+
while ((access_next != access_prev) && (access_prev->next != access_next)) {
119+
access_next = access_next->next;
120+
access_prev = access_prev->prev;
121+
}
122+
list_del(access_prev);
123+
q_release_element(list_entry(access_prev, element_t, list));
114124
return true;
115125
}
116126

0 commit comments

Comments
 (0)