Hi there,
Recently, on some class I'm having at university, the teacher talked about "queues" using the well known linked-list format but with another structure added to the problem. I bet you are already familiar with this stuff so you probably know more than me (that's why I'm posting this here in the first place). Anyway, the structures are these:
Code:
typedef struct sNode {
int elem;
struct sNode *next;
} Node;
typedef struct {
Node *first;
Node *last;
} Queue;
Then, I have the "enqueue" function which was coded like this:
Code:
void enQueue(Queue *q, int elem) {
if(!q) return;
Node *x = (Node*)malloc(sizeof(Node));
if(!x) return;
x->elem = elem;
x->next = NULL;
if(q->last) q->last->next = x; // This line is important to my post!
else q->first = x; // This line is important to my post!
q->last = x; // This line is important to my post!
}
Please note the lines with a comment. Then, on main, I randomize 5 numbers and call the function enQueue with a pre-initialized (with NULL values on 'first' and 'last') queue and the number generated. I also have a function that lists the values on the queue, separated by the linked lists 'first' and 'last'.
After adding 5 numbers to the queue and calling the function that prints the list, the output is this:
Code:
FIRST: 52 -> 38 -> 93 -> 65 -> 27
LAST: 27
Remember the commented lines in the second snippet of code posted? Well, those are the lines that I don't get how they work. I don't understand why the linked-list 'first' has all the numbers generated and why 'last' as only one number which is the last one.
In case it's important, here's the code that prints the "queue":
Code:
void listQueue(Queue q) {
printf("\n\nFIRST: ");
do {
printf("%d", q.first->elem);
q.first = q.first->next;
if(q.first) printf(" -> ");
} while(q.first);
printf("\nLAST: ");
do {
printf("%d", q.last->elem);
q.last = q.last->next;
if(q.last) printf(" -> ");
} while(q.last);
}
Can somebody explain me as easy as possible how those [commented] lines work and what are they doing exactly?
I also have another question but I'll leave that after I understand this bit of code otherwise I'll be much more confused. Home my post is detailed and not confusing...