C语言编程中的堆栈
时间:2020-02-23 14:32:06 来源:igfitidea点击:
堆栈是线性数据结构,包含相同类型的项目。
堆栈遵循后进先出(LIFO)的方式,其中最后输入的元素是要弹出的第一个元素。
在堆栈中,元素的插入和删除仅发生在其一个端点。
1.在堆栈上执行的操作
以下是堆栈所服务的基本操作。
推送:此功能将元素添加到堆栈顶部。
弹出:此函数从堆栈中删除最顶层的元素。
IsEmpty:检查堆栈是否为空。
IsFull:检查堆栈是否已满。
顶部:显示堆栈的最顶部元素。
2.栈的工作
最初,我们设置一个指针Peek/Top来跟踪堆栈中最顶层的项目。
初始化堆栈为-1。
然后,我们通过比较Peek与-1来检查堆栈是否为空,即Top == -1
当我们将元素添加到堆栈中时,Peek元素的位置每次都会更新。
一旦我们从一组输入中弹出或者删除一个项目,最顶层的元素就会被删除,因此Peek/Top的值会减少。
3.在C中实现Stack
堆栈可以使用结构,指针,数组或者链表表示。
其中我们使用C语言中的数组实现了堆栈。
#include<stdio.h>
#include<stdlib.h>
#define Size 4
int Top=-1, inp_array[Size];
void Push();
void Pop();
void show();
int main()
{
int choice;
while(1)
{
printf("\nOperations performed by Stack");
printf("\n1.Push the element\n2.Pop the element\n3.Show\n4.End");
printf("\n\nEnter the choice:");
scanf("%d",&choice);
switch(choice)
{
case 1: Push();
break;
case 2: Pop();
break;
case 3: show();
break;
case 4: exit(0);
default: printf("\nInvalid choice!!");
}
}
}
void Push()
{
int x;
if(Top==Size-1)
{
printf("\nOverflow!!");
}
else
{
printf("\nEnter element to be inserted to the stack:");
scanf("%d",&x);
Top=Top+1;
inp_array[Top]=x;
}
}
void Pop()
{
if(Top==-1)
{
printf("\nUnderflow!!");
}
else
{
printf("\nPopped element: %d",inp_array[Top]);
Top=Top-1;
}
}
void show()
{
if(Top==-1)
{
printf("\nUnderflow!!");
}
else
{
printf("\nElements present in the stack: \n");
for(int i=Top;i>=0;--i)
printf("%d\n",inp_array[i]);
}
}
输出:
Operations performed by Stack 1.Push the element 2.Pop the element 3.Show 4.End Enter the choice:1 Enter element to be inserted to the stack:10 Operations performed by Stack 1.Push the element 2.Pop the element 3.Show 4.End Enter the choice:3 Elements present in the stack: 10 Operations performed by Stack 1.Push the element 2.Pop the element 3.Show 4.End Enter the choice:2 Popped element: 10 Operations performed by Stack 1.Push the element 2.Pop the element 3.Show 4.End Enter the choice:3 Underflow!!
4.堆栈操作的时间复杂度
如上所述,堆栈中一次只能访问一个元素。
在堆栈上执行push()和pop()操作时,需要O(1)时间。

