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, cannot push element.\n'); return; } p->top++; p->data[p->top] = x; }
// 出栈 int pop(SeqStack *p) { if (isEmpty(p)) { printf('Stack is empty, cannot pop element.\n'); return -1; } int x = p->data[p->top]; p->top--; return x; }
// 取栈顶元素 int getTop(SeqStack *p) { if (isEmpty(p)) { printf('Stack is empty, cannot get top element.\n'); return -1; } return p->data[p->top]; }
// 遍历顺序栈 void traverse(SeqStack *p) { if (isEmpty(p)) { printf('Stack is empty.\n'); return; } printf('Stack elements: '); 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 element\n');
printf('2. Pop element\n');
printf('3. Get top element\n');
printf('4. Traverse stack\n');
printf('5. Clear stack\n');
printf('0. Exit\n');
printf('Enter your choice: ');
scanf('%d', &choice);
switch (choice) {
case 1:
printf('Enter the element to push: ');
scanf('%d', &x);
push(&stack, x);
break;
case 2:
x = pop(&stack);
if (x != -1) {
printf('Popped element: %d\n', x);
}
break;
case 3:
x = getTop(&stack);
if (x != -1) {
printf('Top element: %d\n', x);
}
break;
case 4:
traverse(&stack);
break;
case 5:
clearStack(&stack);
printf('Stack cleared.\n');
break;
case 0:
exit(0);
default:
printf('Invalid choice. Please try again.\n');
}
printf('\n');
}
return 0;
}
原文地址: http://www.cveoy.top/t/topic/f3yk 著作权归作者所有。请勿转载和采集!