c语言中实现堆栈

堆栈-stack  原则:后进先出

1.在堆栈上执行的操作 (1. Operations performed on Stacks)

Push: 此功能将元素添加到堆栈顶部   压入

Pop: 此函数从堆栈中删除最顶层的元素  弹出

IsEmpty: 检查堆栈是否为空。

IsFull: 检查堆栈是否已满。

Top: 顶部 :显示堆栈的最顶部元素。

2.栈的工作 (2. Working of Stacks)

最初,我们设置一个指针Peek / Top来跟踪堆栈中最顶层的项目。初始化堆栈为-1。

然后,我们通过比较Peek与-1(即Top == -1)来检查堆栈是否为空

当我们将元素添加到堆栈中时,Peek元素的位置每次都会保持更新。

一旦我们从一组输入中弹出或删除一个项目,最顶层的元素就会被删除,因此Peek / Top的值会减少。

3.在C中实现Stack (3. Implementing Stack in C)

堆栈可以使用结构 , 指针 , 数组或链表表示。

在这里,我们使用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!!
 

  

原文地址: https://blog.csdn.net/cunchi4221/article/details/107471528

  

posted @ 2020-08-18 11:03  souha  阅读(577)  评论(0编辑  收藏  举报