After solving other issues with my struct, my push works as intended however my pop returns the wrong address and I'm not sure why -
QNode* const Q_Pop(Q* const pointerQ){
... // empty check
QNode* tempNode = pointerQ->front.next;
pointerQ->front.next = (tempNode->next);
tempNode->next->prev = &(pointerQ->front);
return tempNode;
}
I'm fairly certain my logic for the actual removal and relinking of the stack is correct but my use of pointers and returning them is messed up.
struct -
struct QueueNode {
struct QueueNode *prev; /* Previous list element. */
struct QueueNode *next; /* Next list element. */
};
typedef struct QueueNode QNode;
struct Queue {
QNode front; // sentinel node at the front of the queue
QNode rear; // sentinel node at the tail of the queue
};
typedef struct Queue Q;
Thanks for the help!
You shouldn't be using "sentinel nodes"; this is pointless and very confusing. A queue can be simply represented as a
QNode*
to the first element. It always points to the first element; if it'sNULL
, the queue is empty; ifelement->next
isNULL
, it's the last element because there isn't a next one. It's very simple to work with that.I didn't test it, but it gives a general idea.
You can push with
push_front()
orcreate_node_front()
(no loops, best performance) then pop withpop_end()
to have a queue effect (FIFO), or pop withpop_front()
to have a stack effect (LIFO).