c语言堆栈程序
Here you will get program for array representation of stack in C.
在这里,您将获得C中堆栈的数组表示形式的程序。
What is Stack?
什么是堆栈?
Stack is a LIFO (last in first out) structure. It is an ordered list of the same type of elements. A stack is a linear list where all insertions and deletions are permitted only at one end of the list. When elements are added to stack it grow at one end. Similarly, when elements are deleted from a stack, it shrinks at the same end.
Stack是LIFO(后进先出)结构。 它是相同类型元素的有序列表。 堆栈是一个线性列表,其中所有插入和删除操作只允许在列表的一端进行。 将元素添加到堆栈时,它的一端会增长。 同样,从堆栈中删除元素时,元素会在同一端缩小。
Also Read: Applications of Stack
另请阅读: 堆栈的应用
Below I have written a C program that performs push, pop and display operations on a stack. It is implemented using 1-D array.
下面,我编写了一个C程序,该程序在堆栈上执行推入,弹出和显示操作。 它是使用一维数组实现的。
C语言栈程序 (Program for Stack in C)
#include<stdio.h>
#include<process.h>
#include<stdlib.h>
#define MAX 5 //Maximum number of elements that can be stored
int top=-1,stack[MAX];
void push();
void pop();
void display();
void main()
{
int ch;
while(1) //infinite loop, will end when choice will be 4
{
printf("\n*** Stack Menu ***");
printf("\n\n1.Push\n2.Pop\n3.Display\n4.Exit");
printf("\n\nEnter your choice(1-4):");
scanf("%d",&ch);
switch(ch)
{
case 1: push();
break;
case 2: pop();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("\nWrong Choice!!");
}
}
}
void push()
{
int val;
if(top==MAX-1)
{
printf("\nStack is full!!");
}
else
{
printf("\nEnter element to push:");
scanf("%d",&val);
top=top+1;
stack[top]=val;
}
}
void pop()
{
if(top==-1)
{
printf("\nStack is empty!!");
}
else
{
printf("\nDeleted element is %d",stack[top]);
top=top-1;
}
}
void display()
{
int i;
if(top==-1)
{
printf("\nStack is empty!!");
}
else
{
printf("\nStack is...\n");
for(i=top;i>=0;--i)
printf("%d\n",stack[i]);
}
}
Output
输出量
*** Stack Menu ***
***堆栈菜单***
1.Push 2.Pop 3.Display 4.Exit
1.Push 2.Pop 3.显示 一,进入
Enter your choice(1-4):1
输入您的选择(1-4):1
Enter element to push:3
输入要推送的元素:3
*** Stack Menu ***
***堆栈菜单***
1.Push 2.Pop 3.Display 4.Exit
1.Push 2.Pop 3.显示 一,进入
Enter your choice(1-4):1
输入您的选择(1-4):1
Enter element to push:6
输入要推送的元素:6
*** Stack Menu ***
***堆栈菜单***
1.Push 2.Pop 3.Display 4.Exit
1.Push 2.Pop 3.显示 一,进入
Enter your choice(1-4):3
输入您的选择(1-4):3
Stack is… 6 3
堆栈是… 6 3
*** Stack Menu ***
***堆栈菜单***
1.Push 2.Pop 3.Display 4.Exit
1.Push 2.Pop 3.显示 一,进入
Enter your choice(1-4):2
输入您的选择(1-4):2
Deleted element is 6 *** Stack Menu ***
删除的元素是6 ***堆栈菜单***
1.Push 2.Pop 3.Display 4.Exit
1.Push 2.Pop 3.显示 一,进入
Enter your choice(1-4):3
输入您的选择(1-4):3
Stack is… 3
堆栈是… 3
*** Stack Menu ***
***堆栈菜单***
1.Push 2.Pop 3.Display 4.Exit
1.Push 2.Pop 3.显示 一,进入
Enter your choice(1-4):2
输入您的选择(1-4):2
Deleted element is 3 *** Stack Menu ***
删除的元素是3 ***堆栈菜单***
1.Push 2.Pop 3.Display 4.Exit
1.Push 2.Pop 3.显示 一,进入
Enter your choice(1-4):2
输入您的选择(1-4):2
Stack is empty!!
堆栈是空的!
影片教学 (Video Tutorial)
c语言堆栈程序