Looking at your code, the issue is that queue_peek is returning the last element in the queue rather than the first element (which is what peek typically should do).
The function traverses to find the second-to-last node (queueRunning->next->next == NULL) and then returns queueRunning->next, which is the last node. This would be appropriate for a stack's peek operation, but queues typically follow FIFO (First In, First Out) ordering where peek should return the element that would be dequeued next - the first element.
Here's what's happening:
The while loop finds the node whose next->next is NULL
This means queueRunning is the second-to-last node
You return queueRunning->next, which is the last node
If you want to peek at the first element in the queue (assuming queue points to a dummy head node), you should simply return:
c
void *queue_peek(queue_object *queue)
{
if (queue == NULL) {
printf("Queue head is empty");
return NULL;
}
if (!queue->next) return NULL;
return queue->next; // Return the first actual element
}
If your queue doesn't use a dummy head and queue itself is the first element, then you'd just return queue.
The current implementation would make sense if you're trying to peek at the last element added to the queue, but that's unusual for a standard queue peek operation.