什么是堆栈?
堆栈是一种特殊的数据结构,其中元素从一端输入,从同一端删除。
堆栈也称为后进先出数据结构[LIFO]。因为最后输入的元素将首先被删除。
以下是Stack的图片示例:
以下是可以在堆栈上执行的各种操作:
- 推: 插入要堆叠的元素
- 流行: 从堆栈中删除元素
- 溢出: 检查堆栈是否已满
- 下流: 检查堆栈是否为空。
- 显示: 显示堆栈中的内容。
以下是我们将要使用的重要功能:
1.推():
我们使用推入操作将元素插入堆栈。在这里,在将元素推入堆栈之前,我们应确保堆栈具有足够的空间用于该操作。
可以通过检查当前堆栈大小和最大堆栈大小来完成。如果当前堆栈大小小于最大堆栈大小,那么我们将插入元素并将当前堆栈大小增加一。
以下是推送操作的图形示例:
在这里,我们将10、20、30、40插入堆栈。
2.弹出():
我们使用pop从堆栈中删除/删除元素。在删除元素之前,我们需要检查堆栈中是否包含某些元素。
从没有元素的堆栈中删除元素会导致堆栈下溢。
下面是弹出操作的图形示例:
在这里,我们从堆栈中删除40、30、20、10。
3. 显示()
Display方法用于显示堆栈中的所有元素。如果没有元素,则应显示相应的错误消息。
堆栈可以通过两种方式实现。
- 使用数组
- 使用链表
在本教程中,我们将看到如何使用数组实现堆栈。在下一个教程中,我们将看到如何使用链表实现堆栈。
使用数组实现堆栈的C程序:
#include<stdio.h> #include<stdlib.h> #define STACK_SIZE 5 int top_index = 0; /* Variable to hold top index */ int 叠_items[10]; /* Array to hold 叠 items */ int item = 0; /* Variable to hold the value to be inserted into 叠*/ //function to check if 叠 is full int IsFull() { return (top_index == STACK_SIZE - 1); } //function to insert an element in 叠 void push() { if (IsFull()) { printf("Stack is full. Cannot insert more elements \n"); return; } top_index = top_index + 1; stack_items[top_index] = item; } //function to check if the 叠 is empty int IsEmpty() { return top_index == -1; } //function to delete an element in 叠 int pop () { if (IsEmpty()) { return -1; } return 叠_items[top_index --]; } // function to display elements in the 叠 void display() { if(top_index == -1) { printf("Stack is empty\n"); return; } printf("The contents of the 叠 are:\n"); for (int i = 0; i <= top_index; ++i) { printf("%d\n", 叠_items[i]); } return; } int main() { int deleted_item = 0; int choice = 0; top_index = -1; for( ; ; ) { printf("1. Push \n2. Pop \n3. Display \n4. Exit\n"); scanf("%d", &choice); switch(choice) { case 1: printf("\nEnter the item to be inserted\n"); scanf("%d", &item); push(); break; case 2: deleted_item = pop(); if(deleted_item == -1) { printf("Stack is empty\n"); } else { printf("Deleted Item = %d\n",deleted_item ); } break; case 3: display(); break; default: exit(0); } } return 0; }
输出:
1. Push 2. Pop 3. Display 4. Exit 3 Stack is empty 1. Push 2. Pop 3. Display 4. Exit 1 Enter the item to be inserted 2 1. Push 2. Pop 3. Display 4. Exit 1 Enter the item to be inserted 3 1. Push 2. Pop 3. Display 4. Exit 3 The contents of the 叠 are: 2 3 1. Push 2. Pop 3. Display 4. Exit 2 Deleted Item = 3 1. Push 2. Pop 3. Display 4. Exit 3 The contents of the 叠 are: 2 1. Push 2. Pop 3. Display 4. Exit 4
进一步阅读:
AJ关于DS和算法的权威指南。单击此处以学习算法和数据结构教程的完整列表。 85多个章节可供学习。
该网站上可用的教程列表:
C编程20+章 | C ++编程80+章 |
100多个编码问题 | 数据结构和算法85+章 |
系统设计20+章 | Shell脚本编写12章 |
4g LTE 60+章节 | 最常见的编码问题 |
5G NR 50+章 | Linux系统编程20+章 |