在C語言中,可以使用結(jié)構(gòu)體數(shù)組來實(shí)現(xiàn)棧和隊(duì)列。以下是一個(gè)簡單的示例:
#include <stdio.h>
#include <stdbool.h>
// 定義棧的結(jié)構(gòu)體
typedef struct {
int data[100]; // 存儲(chǔ)數(shù)據(jù)的數(shù)組
int top; // 棧頂指針
} Stack;
// 初始化棧
void initStack(Stack *s) {
s->top = -1;
}
// 入棧操作
void push(Stack *s, int value) {
if (s->top >= 99) {
printf("棧已滿,無法入棧
");
return;
}
s->data[++s->top] = value;
}
// 出棧操作
int pop(Stack *s) {
if (s->top < 0) {
printf("棧為空,無法出棧
");
return -1;
}
return s->data[s->top--];
}
// 判斷棧是否為空
bool isEmpty(Stack *s) {
return s->top == -1;
}
// 定義隊(duì)列的結(jié)構(gòu)體
typedef struct {
int data[100]; // 存儲(chǔ)數(shù)據(jù)的數(shù)組
int front; // 隊(duì)首指針
int rear; // 隊(duì)尾指針
} Queue;
// 初始化隊(duì)列
void initQueue(Queue *q) {
q->front = q->rear = -1;
}
// 入隊(duì)操作
void enqueue(Queue *q, int value) {
if ((q->rear + 1) % 100 == q->front) {
printf("隊(duì)列已滿,無法入隊(duì)
");
return;
}
q->rear = (q->rear + 1) % 100;
q->data[q->rear] = value;
if (q->front == -1) {
q->front = q->rear;
}
}
// 出隊(duì)操作
int dequeue(Queue *q) {
if (q->front == -1) {
printf("隊(duì)列為空,無法出隊(duì)
");
return -1;
}
int value = q->data[q->front];
if (q->front == q->rear) {
q->front = q->rear = -1;
} else {
q->front = (q->front + 1) % 100;
}
return value;
}
// 判斷隊(duì)列是否為空
bool isQueueEmpty(Queue *q) {
return q->front == -1;
}
這個(gè)示例中,我們定義了兩個(gè)結(jié)構(gòu)體:Stack
用于實(shí)現(xiàn)棧,Queue
用于實(shí)現(xiàn)隊(duì)列。每個(gè)結(jié)構(gòu)體都有一個(gè)數(shù)組data
來存儲(chǔ)數(shù)據(jù),以及一個(gè)或兩個(gè)指針(top
、front
和rear
)來表示棧頂或隊(duì)列的頭部和尾部位置。我們還提供了一些基本的棧和隊(duì)列操作函數(shù),如push
、pop
、enqueue
、dequeue
等。