c++动态分配的char*队列
时间: 2023-09-13 08:14:07 浏览: 40
您好!关于动态分配的char*队列,您可以考虑使用链表来实现。具体的实现步骤可以参考下面的代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 节点结构体
typedef struct node {
char* data; // 数据域
struct node* next; // 指针域
} Node;
// 队列结构体
typedef struct queue {
Node* front; // 队头指针
Node* rear; // 队尾指针
} Queue;
// 初始化队列
void initQueue(Queue* q) {
q->front = q->rear = NULL;
}
// 判断队列是否为空
int isEmptyQueue(Queue* q) {
return q->front == NULL;
}
// 入队操作
void enQueue(Queue* q, char* data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = (char*)malloc(strlen(data) + 1);
strcpy(newNode->data, data);
newNode->next = NULL;
if (isEmptyQueue(q)) {
q->front = q->rear = newNode;
} else {
q->rear->next = newNode;
q->rear = newNode;
}
}
// 出队操作
char* deQueue(Queue* q) {
if (isEmptyQueue(q)) {
return NULL;
}
Node* temp = q->front;
char* data = temp->data;
q->front = q->front->next;
if (q->front == NULL) {
q->rear = NULL;
}
free(temp);
return data;
}
// 测试代码
int main() {
Queue q;
initQueue(&q);
enQueue(&q, "Hello");
enQueue(&q, "World");
enQueue(&q, "ChitGPT");
while (!isEmptyQueue(&q)) {
printf("%s ", deQueue(&q));
}
return 0;
}
```
上述代码中使用了链表来实现队列,并且为每个节点的数据域动态分配了内存空间。您可以根据自己的实际需求对代码进行修改。希望对您有所帮助!