In this blog, I am going to discuss the basic data structure of stack. This is a very basic article, which might be helpful for the fresh students or beginners.
Introduction
In general, we use the word stack for a bundle of packets or pile of plates .The things which are placed on one over another till the top/peek is called a stack.
Stack
In programming world, we use stack to store data at a runtime on temporary basis. In stack data structure, we use two types of operations, which are as follows.
- PUSH
- POP
The logic which is used behind these operations are Last In First Out(LIFO). LIFO is a method, which tells us that the thing which is PUSH last should be POP first.
Now, we are moving forward to our implementation, which is coded on C sharp
First, we declare three variables to control our stack .The reason for these variables are mentioned in the comments.
- int max = 3; // Size of the Stack , You can handle the size of your stack dynamically
- int top = -1; // it is a pointer which keep track that whether your stack is filled or not
- string respnse = " "; // this variable is used to store your response whether you want to PUSH or POP
- string[] array = new string[max]; //Here we declare an array for our stack implementation
- while (true) {
- Console.WriteLine("Press P for push and O for POP");
- respnse = Console.ReadLine().ToUpper();
- if (respnse == "P") {
- Console.WriteLine("Enter value");
- top = top + 1; // on Pushing each value stack counter will be incremented
- if (top == max) {
- Console.WriteLine("Stack overflow");
- return;
- }
- array[top] = Console.ReadLine();
- }
- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - x-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - x-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
- This is an accumulated code
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace stackNque {
- class Program {
- static void Main(string[] args) {
- int max = 3;
- int top = -1;
- string respnse = "";
- string[] array = new string[max];
- while (true) {
- Console.WriteLine("Press P for push and O for POP");
- respnse = Console.ReadLine().ToUpper();
- if (respnse == "P") {
- Console.WriteLine("Enter value");
- top = top + 1;
- if (top == max) {
- Console.WriteLine("Stack overflow");
- return;
- }
- array[top] = Console.ReadLine();
- }
- if (respnse == "O") {
- array[top] = " ";
- top = top - 1;
- if (top < max) {
- Console.WriteLine("Stack Underflow");
- }
- }
- }
- }
- }
- }
Stack is a container, where we insert our data in a pile. It is most useful where we track our last insertion record or use old data on a first level.
We can do PUSH and PULL operations on the basis of LIFO method.
Join the conversation! Your thoughts help the community grow.