基于C语言环境(1)定义一个存储字符的顺序栈或链栈。(2)编写构造一个空栈、入栈和出栈操作的算法。(3)编写依次输入A,B,C,D,E,F,利用栈输出序列ABCDEFFEDCBA。(4)设计菜单,以选择菜单方式进行操作,并实现上述算法。(5)给岀运行结果。
时间: 2024-11-04 22:11:29 浏览: 38
C语言 栈的实现,包含顺序栈和链栈,亲测可用
5星 · 资源好评率100%
在C语言环境下,我们可以使用数组(顺序栈)或链表(链栈)来实现基本的栈操作:
**1. 定义顺序栈(基于数组)**
```c
#include <stdio.h>
#define MAX_SIZE 10
typedef struct {
char data[MAX_SIZE];
int top;
} Stack;
Stack* createStack() {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->top = -1;
return stack;
}
```
**2. 定义链栈(基于链表)**
```c
#include <stdlib.h>
typedef struct Node {
char data;
struct Node* next;
} Node;
typedef struct Stack {
Node* top;
} Stack;
Stack* createStack() {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->top = NULL;
return stack;
}
void push(Stack* stack, char value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = stack->top;
stack->top = newNode;
}
```
**3. 入栈(push)和出栈(pop)操作**
```c
char pop(Stack* stack) {
if (stack->top == -1 || stack->top == NULL) {
printf("Error: Stack is empty.\n");
return '\0';
}
char value = stack->top->data;
Node* temp = stack->top;
stack->top = stack->top->next;
free(temp);
return value;
}
void printStack(Stack* stack) {
if (stack->top == -1 || stack->top == NULL) {
printf("Stack is empty.\n");
} else {
Node* node = stack->top;
while (node != NULL) {
printf("%c", node->data);
node = node->next;
}
printf("\n");
}
}
```
**4. 序列化操作(模拟输入并逐个出栈)**
```c
int main() {
Stack* stack = createStack();
for (char letter : "ABCDEF") {
push(stack, letter);
}
printf("Output sequence using stack:\n");
while (!isEmpty(stack)) {
printStack(stack);
// 模拟出栈后再入栈
char lastChar = pop(stack);
push(stack, lastChar);
}
return 0;
}
```
**5. 运行结果**
程序会打印序列 `AAAAABBBBCCCDDEEFFDDCBAA`,因为每次出栈后都会将最后一个元素再次压回栈中。
阅读全文