I have a file queue.c that defines a Queue in C. How would I make 3 separate queues independent of each other? I'm not very experienced with C, and I keep thinking of it in an OO view, and I know that I can't do that.
#include <stdio.h>
#include <stdlib.h>
struct Node
{
char data;
struct Node *next;
} *Head, *Tail;
void addCharacter(char c)
{
struct Node *temp1, *temp2;
temp1 = (struct Node *)malloc(sizeof(struct Node));
temp1->data = c;
temp2 = Tail;
if(Head == NULL)
{
Head = temp1;
Head->next = NULL;
Tail = Head;
}
else
{
Tail = temp1;
temp1->next = NULL;
temp2->next = temp1;
}
}
void deleteCharacter()
{
struct Node *temp1 = Head;
Head = temp1->next;
free(temp1);
}
int replaceCharacter(char c)
{
Head->data = c;
}
int main() {}
That's my Queue, and all I have for another C file is essentially:
#include "queue.h"
I don't know where to go from there...
Instead of making Head
and Tail
global variables, make another struct that contains them, eg:
struct Queue {
struct Node *head;
struct Node *tail;
};
Then change your functions operating on a queue to take a pointer to a Queue
struct, and operate on that.
You will also want a initQueue
function that initializes head
and tail
to NULL
. Then using a queue can look like:
struct Queue queue1;
initQueue(&queue1);
addCharacter(&queue1, 'a');
//....
You could just define a new structure for queue.
struct Node
{
char data;
struct Node *next;
};
struct Queue
{
struct Node *Head, *Tail;
// optional int size;
};
And then for each function add another parameter:
void addCharacter(struct Queue *q, char c);
void deleteCharacter(struct Queue *q);
And access with q->Head
and q->Tail
.
Did you design this queue library? In its current form you cannot have more than one queue because the function use the global pointers Head
and Tail
and there no way to tell your functions to use some other pointers.
You have a global Head
and Tail
. If you want multiple lists, you need multiple heads. So you will need to change your functions so that &Head
and &Tail
are parameters.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.