C语言·双栈初始化、判断栈空、栈满、进栈和出栈运算的实现算法; 设计测试数据(设m=6,数组为整型数组)
时间: 2024-11-22 22:37:44 浏览: 30
在C语言中,我们可以使用链表来实现双栈(通常称为前后两端都能操作的栈)。下面是一个基础的实现,包括栈的初始化、检查栈是否为空、判断栈是否已满(这里默认栈的最大容量为给定的常量`m`)、入栈(`push`)和出栈(`pop`)操作。
```c
#include <stdio.h>
#include <stdlib.h>
// 定义栈节点结构
typedef struct Node {
int data;
struct Node* next; // 指向下一个节点
struct Node* prev; // 指向前一个节点
} StackNode;
// 双栈结构体
typedef struct DoublyStack {
StackNode* top; // 栈顶
StackNode* bottom; // 栈底
int capacity; // 栈的最大容量
int size; // 当前栈内元素数
} DoublyStack;
// 初始化双栈
DoublyStack* initDoublyStack(int m) {
DoublyStack* stack = (DoublyStack*)malloc(sizeof(DoublyStack));
stack->top = stack->bottom = NULL;
stack->capacity = m;
stack->size = 0;
return stack;
}
// 判断栈是否为空
int isEmpty(DoublyStack* stack) {
return stack->top == NULL;
}
// 判断栈是否已满
int isFull(DoublyStack* stack) {
return stack->size == stack->capacity;
}
// 进栈操作(在栈的后端添加元素)
void push(DoublyStack* stack, int value) {
if (isFull(stack)) {
printf("Stack is full.\n");
return;
}
StackNode* new_node = (StackNode*)malloc(sizeof(StackNode));
new_node->data = value;
new_node->prev = stack->bottom;
if (stack->top != NULL) {
stack->top->prev = new_node;
}
stack->top = new_node;
stack->size++;
stack->bottom->next = NULL;
}
// 出栈操作(删除并返回栈顶元素,如果栈为空则报错)
int pop(DoublyStack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty.\n");
return -1;
}
int value = stack->top->data;
StackNode* node = stack->top;
stack->top = node->prev;
if (stack->top == NULL) {
stack->bottom = NULL;
} else {
stack->top->next = NULL;
}
free(node);
stack->size--;
return value;
}
// 示例测试
int main() {
int m = 6;
DoublyStack* ds = initDoublyStack(m);
for (int i = 1; i <= m; i++) {
push(ds, i);
printf("Pushed: %d\n", i);
}
for (int i = 1; i <= m; i++) {
int popped = pop(ds);
printf("Popped: %d\n", popped);
}
free(ds);
return 0;
}
```
阅读全文