1. 程式人生 > 實用技巧 >c語言中實現堆疊

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