C语言顺序栈实现及基本操作示例代码
#include <stdio.h> #include <stdlib.h>
#define MAXSIZE 100
typedef struct { int data[MAXSIZE]; int top; } SeqStack;
// 初始化顺序栈 void InitStack(SeqStack *p) { p->top = -1; }
// 判断栈是否为空 int IsEmpty(SeqStack *p) { return p->top == -1; }
// 判断栈是否为满 int IsFull(SeqStack *p) { return p->top == MAXSIZE - 1; }
// 插入元素 void Push(SeqStack *p, int x) { if (IsFull(p)) { printf('Stack is full.\n'); return; } p->data[++p->top] = x; }
// 删除栈顶元素 void Pop(SeqStack *p) { if (IsEmpty(p)) { printf('Stack is empty.\n'); return; } p->top--; }
// 取栈顶元素 int Top(SeqStack *p) { if (IsEmpty(p)) { printf('Stack is empty.\n'); exit(1); } return p->data[p->top]; }
// 遍历顺序栈 void Traverse(SeqStack *p) { if (IsEmpty(p)) { printf('Stack is empty.\n'); return; } for (int i = 0; i <= p->top; i++) { printf('%d ', p->data[i]); } printf('\n'); }
// 置空顺序栈 void ClearStack(SeqStack *p) { p->top = -1; }
int main() { SeqStack stack; InitStack(&stack);
int choice, x;
while (1) {
printf('1. Push\n');
printf('2. Pop\n');
printf('3. Top\n');
printf('4. Traverse\n');
printf('5. Clear Stack\n');
printf('0. Exit\n');
printf('Enter your choice: ');
scanf('%d', &choice);
switch (choice) {
case 1:
printf('Enter the number to push: ');
scanf('%d', &x);
Push(&stack, x);
break;
case 2:
Pop(&stack);
break;
case 3:
printf('Top element: %d\n', Top(&stack));
break;
case 4:
Traverse(&stack);
break;
case 5:
ClearStack(&stack);
break;
case 0:
exit(0);
default:
printf('Invalid choice.\n');
break;
}
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/f3yj 著作权归作者所有。请勿转载和采集!