C 语言栈程序
C 语言栈实现
以下是栈 ADT 中基本操作(push()、pop()、peek()、isEmpty()、isFull())的实现,并使用 C 语言 − 打印输出。
#include <stdio.h>
int MAXSIZE = 8;
int stack[8];
int top = -1;
/* 检查栈是否为空 */
int isempty(){
if(top == -1)
return 1;
else
return 0;
}
/* 检查堆栈是否已满 */
int isfull(){
if(top == MAXSIZE)
return 1;
else
return 0;
}
/* 返回栈顶元素的函数 */
int peek(){
return stack[top];
}
/* 从栈中删除元素的函数 */
int pop(){
int data;
if(!isempty()) {
data = stack[top];
top = top - 1;
return data;
} else {
printf("Could not retrieve data, Stack is empty.
");
}
}
/* 插入堆栈的函数 */
int push(int data){
if(!isfull()) {
top = top + 1;
stack[top] = data;
} else {
printf("Could not insert data, Stack is full.
");
}
}
/* Main function */
int main(){
push(44);
push(10);
push(62);
push(123);
push(15);
printf("Element at top of the stack: %d
" ,peek());
printf("Elements:
");
// print stack data
while(!isempty()) {
int data = pop();
printf("%d
",data);
}
printf("Stack full: %s
" , isfull()?"true":"false");
printf("Stack empty: %s
" , isempty()?"true":"false");
return 0;
}
输出
Element at top of the stack: 15 Elements: 15123 62 10 44 Stack full: false Stack empty: true

stack_algorithm.html