当前位置: 首页 > 文档资料 > 数据结构和算法 >

点击这里

优质
小牛编辑
124浏览
2023-12-01

我们将在这里看到C编程语言中的堆栈实现。 您可以通过单击Try-it按钮来尝试该程序。 要了解堆栈的理论方面,请单击访问上一页。

用C实现 (Implementation in 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.\n");
   }
}
int push(int data) {
   if(!isfull()) {
      top = top + 1;   
      stack[top] = data;
   } else {
      printf("Could not insert data, Stack is full.\n");
   }
}
int main() {
   // push items on to the stack 
   push(3);
   push(5);
   push(9);
   push(1);
   push(12);
   push(15);
   printf("Element at top of the stack: %d\n" ,peek());
   printf("Elements: \n");
   // print stack data 
   while(!isempty()) {
      int data = pop();
      printf("%d\n",data);
   }
   printf("Stack full: %s\n" , isfull()?"true":"false");
   printf("Stack empty: %s\n" , isempty()?"true":"false");
   return 0;
}

如果我们编译并运行上面的程序,它将产生以下结果 -

输出 (Output)

Element at top of the stack: 15
Elements:
15
12
1 
9 
5 
3 
Stack full: false
Stack empty: true