Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Data Structures in C

Tags:

c

object

queue

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...

like image 687
Atrus Avatar asked Jun 28 '26 08:06

Atrus


2 Answers

Instead of making Head and Tail global variables, make another struct that contains them, e.g.:

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');
//....
like image 167
interjay Avatar answered Jun 30 '26 21:06

interjay


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.

like image 33
Iustin Avatar answered Jun 30 '26 20:06

Iustin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!