使用c语言实现栈和队列的基本操作的全部代码(只写顺序栈和顺序队列)
时间: 2024-12-11 11:30:11 浏览: 9
在C语言中,我们可以使用数组来实现简单的栈(后进先出LIFO,Last In First Out)和队列(先进先出FIFO,First In First Out)。这里提供基本操作的示例代码:
**栈(Sequence Stack)**
```c
#include <stdio.h>
#define MAX_SIZE 50
typedef struct {
int top;
int arr[MAX_SIZE];
} Stack;
// 初始化栈
void init(Stack* stack) {
stack->top = -1;
}
// 判断栈是否满
int isFull(Stack* stack) {
return stack->top == MAX_SIZE - 1;
}
// 判断栈是否空
int isEmpty(Stack* stack) {
return stack->top == -1;
}
// 入栈
void push(Stack* stack, int value) {
if (isFull(stack)) {
printf("Stack Overflow!\n");
return;
}
stack->arr[++stack->top] = value;
}
// 出栈
int pop(Stack* stack) {
if (isEmpty(stack)) {
printf("Stack Underflow!\n");
return -1;
}
return stack->arr[stack->top--];
}
// 获取栈顶元素(查看,不弹出)
int peek(Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty.\n");
return -1;
}
return stack->arr[stack->top];
}
int main() {
Stack s;
init(&s);
push(&s, 1); // 入栈1
push(&s, 2); // 入栈2
printf("Top element is: %d\n", peek(&s)); // 查看栈顶元素
printf("%d popped from stack.\n", pop(&s)); // 出栈并打印
return 0;
}
```
**队列(Sequence Queue)**
```c
#include <stdio.h>
#define MAX_SIZE 50
typedef struct {
int front;
int rear;
int arr[MAX_SIZE];
} Queue;
// 初始化队列
void init(Queue* queue) {
queue->front = queue->rear = -1;
}
// 判断队列是否满
int isFull(Queue* queue) {
return queue->rear == (queue->front + 1) % MAX_SIZE;
}
// 判断队列是否空
int isEmpty(Queue* queue) {
return queue->front == queue->rear;
}
// 入队
void enqueue(Queue* queue, int value) {
if (isFull(queue)) {
printf("Queue Overflow!\n");
return;
}
queue->arr[(queue->rear + 1) % MAX_SIZE] = value;
queue->rear = (queue->rear + 1) % MAX_SIZE;
}
// 出队
int dequeue(Queue* queue) {
if (isEmpty(queue)) {
printf("Queue Underflow!\n");
return -1;
}
int value = queue->arr[queue->front];
queue->front = (queue->front + 1) % MAX_SIZE;
return value;
}
int main() {
Queue q;
init(&q);
enqueue(&q, 1); // 入队1
enqueue(&q, 2); // 入队2
printf("Front element of the queue is: %d\n", dequeue(&q)); // 出队并打印
return 0;
}
```
**
阅读全文