gpt4 book ai didi

c - C 中的多个数据结构

转载 作者:太空狗 更新时间:2023-10-29 15:49:28 24 4
gpt4 key购买 nike

我有一个文件 queue.c,它在 C 中定义了一个队列。我如何使 3 个独立的队列相互独立?我对 C 不是很有经验,我一直在 OO View 中思考它,我知道我不能那样做。

#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() {}

那是我的队列,我对另一个 C 文件所拥有的基本上是:

#include "queue.h"

我不知道从那里去哪里......

最佳答案

不是制作 HeadTail 全局变量,而是制作另一个包含它们的结构,例如:

struct Queue {
struct Node *head;
struct Node *tail;
};

然后更改在队列上操作的函数以获取指向 Queue 结构的指针,并对其进行操作。

您还需要一个initQueue 函数来将headtail 初始化为NULL。然后使用队列可以看起来像:

struct Queue queue1;
initQueue(&queue1);
addCharacter(&queue1, 'a');
//....

关于c - C 中的多个数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5795004/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com