I'm having a tough time wrapping my head around C. I'm trying to implement a FIFO linked list where I have a reference to the tail-end of the list for easy access when adding elements. Enqueuing to an empty list works fine where the head and rear would be the same Node. However, when I enqueue for a second time, the rear is correctly the new Node but the head is also updated, which should stay the same. Any thoughts to what I might be doing wrong? I apologize in advance for the one-liner conditional if it's difficult to read.
typedef struct node {
PCB *pcb;
struct node *next;
}Node;
typedef struct queue {
Node *head, *rear;
int size;
}Queue;
Queue * enqueue (Queue *queue, PCB *pcb) {
// Ready a new node to add to list:
Node node = {pcb, NULL};
// Node becomes head in empty list, otherwise appended to rear.
queue->size == 0 ? (queue->head = queue->rear = &node) : (queue->rear = &node);
// Keep track of list size
queue->size++;
return queue;
}
UPDATED:
Queue * enqueue (Queue *queue, PCB *pcb) {
// Ready a new node to add to list:
Node *node = malloc(sizeof(Node));
node->pcb = pcb;
node->next = NULL;
// Node becomes head in empty list, otherwise appended to rear.
queue->size == 0 ? (queue->head = queue->rear = node) : (queue->rear->next = node);
// New node always becomes the new rear node
queue->rear = node;
// Keep track of list size
queue->size++;
return queue;
}