When the position of the top of stack is equivalent to 0 this means that?

Non-essential operationsEdit

In many implementations, a stack has more operations than the essential "push" and "pop" operations. An example of a non-essential operation is "top of stack", or "peek", which observes the top element without removing it from the stack.[17] This could be done with a "pop" followed by a "push" to return the same data to the stack, so it is not considered an essential operation. If the stack is empty, an underflow condition will occur upon execution of either the "stack top" or "pop" operations. Additionally, many implementations provide a check if the stack is empty and one that returns its size.

Software stacksEdit

ImplementationEdit

A stack can be easily implemented either through an array or a linked list. What identifies the data structure as a stack, in either case, is not the implementation but the interface: the user is only allowed to pop or push items onto the array or linked list, with few other helper operations. The following will demonstrate both implementations, using pseudocode.

ArrayEdit

An array can be used to implement a (bounded) stack, as follows. The first element, usually at the zero offset, is the bottom, resulting in array[0] being the first element pushed onto the stack and the last element popped off. The program must keep track of the size (length) of the stack, using a variable top that records the number of items pushed so far, therefore pointing to the place in the array where the next element is to be inserted (assuming a zero-based index convention). Thus, the stack itself can be effectively implemented as a three-element structure:

structure stack: maxsize: integer top: integer items: array of item procedure initialize(stk: stack, size: integer): stk.items ← new array of size items, initially empty stk.maxsize ← size stk.top ← 0

The push operation adds an element and increments the top index, after checking for overflow:

procedure push(stk: stack, x: item): if stk.top = stk.maxsize: report overflow error else: stk.items[stk.top] ← x stk.top ← stk.top + 1

Similarly, pop decrements the top index after checking for underflow, and returns the item that was previously the top one:

procedure pop(stk: stack): if stk.top = 0: report underflow error else: stk.top ← stk.top − 1 r ← stk.items[stk.top] return r

Using a dynamic array, it is possible to implement a stack that can grow or shrink as much as needed. The size of the stack is simply the size of the dynamic array, which is a very efficient implementation of a stack since adding items to or removing items from the end of a dynamic array requires amortized O(1) time.

Linked listEdit

Another option for implementing stacks is to use a singly linked list. A stack is then a pointer to the "head" of the list, with perhaps a counter to keep track of the size of the list:

structure frame: data: item next: frame or nil structure stack: head: frame or nil size: integer procedure initialize(stk: stack): stk.head ← nil stk.size ← 0

Pushing and popping items happens at the head of the list; overflow is not possible in this implementation (unless memory is exhausted):

procedure push(stk: stack, x: item): newhead ← new frame newhead.data ← x newhead.next ← stk.head stk.head ← newhead stk.size ← stk.size + 1 procedure pop(stk: stack): if stk.head = nil: report underflow error r ← stk.head.data stk.head ← stk.head.next stk.size ← stk.size - 1 return r

Stacks and programming languagesEdit

Some languages, such as Perl, LISP, JavaScript and Python, make the stack operations push and pop available on their standard list/array types. Some languages, notably those in the Forth family (including PostScript), are designed around language-defined stacks that are directly visible to and manipulated by the programmer.

The following is an example of manipulating a stack in Common Lisp (">" is the Lisp interpreter's prompt; lines not starting with ">" are the interpreter's responses to expressions):

> (setf stack (list 'a 'b 'c)) ;; set the variable "stack" (A B C) > (pop stack) ;; get top (leftmost) element, should modify the stack A > stack ;; check the value of stack (B C) > (push 'new stack) ;; push a new top onto the stack (NEW B C)

Several of the C++ Standard Library container types have push_back and pop_back operations with LIFO semantics; additionally, the stack template class adapts existing containers to provide a restricted API with only push/pop operations. PHP has an SplStack class. Java's library contains a Stack class that is a specialization of Vector. Following is an example program in Java language, using that class.

import java.util.Stack; class StackDemo { public static void main(String[]args) { Stack stack = new Stack(); stack.push("A"); // Insert "A" in the stack stack.push("B"); // Insert "B" in the stack stack.push("C"); // Insert "C" in the stack stack.push("D"); // Insert "D" in the stack System.out.println(stack.peek()); // Prints the top of the stack ("D") stack.pop(); // removing the top ("D") stack.pop(); // removing the next top ("C") } }

Stack and its basic Operations

What is stack?

First, let us see the properties of data structures that we already do know and build-up our concepts towards the stack.

  • Array: Its a random-access container, meaning any element of this container can be accessed instantly
  • Linked List: It's a sequential-access container, meaning that elements of this data structure can only be accessed sequentially

→ Following a similar definition, a stack is a container where only the top element can be accessed or operated upon.

A Stack is a data structure following the LIFO(Last In, First Out) principle.

If you have trouble visualizing stacks, just assume a stack of books.

  • In a stack of books, you can only see the top book
  • If you want to access any other book, you would first need to remove the books on top of it
  • The bottom-most book in the stack was put first and can only be removed at the last after all books on top of it have been removed.
PUSH Operation

Push operation refers to inserting an element in the stack. Since there’s only one position at which the new element can be inserted — Top of the stack, the new element is inserted at the top of the stack.

POP Operation

Pop operation refers to the removal of an element. Again, since we only have access to the element at the top of the stack, there’s only one element that we can remove. We just remove the top of the stack. Note: We can also choose to return the value of the popped element back, its completely at the choice of the programmer to implement this.

PEEK Operation

Peek operation allows the user to see the element on the top of the stack. The stack is not modified in any manner in this operation.

isEmpty: Check if stack is empty or not

To prevent performing operations on an empty stack, the programmer is required to internally maintain the size of the stack which will be updated during push and pop operations accordingly. isEmpty() conventionally returns a boolean value: True if size is 0, else False.

Stack Implementation

As we’ve learned before, Stack is a very useful concept that a good programmer could use to his/her benefit. But can you implement it in your code yet? It's not that difficult once you think about it, let’s walk through its properties and implement them in code.

You should remember one very important thing though →

All operations in the stack must be of O(1) time complexity

We shall be implementing stack in two different ways by changing the underlying container: Array and Linked List.

1. Array Implementation

An array is one of the simplest containers offering random access to users based on indexes. But can we access any element of the stack at any given time? No. That’s why we need to set an index as top and then access only the element at index top.

int stack[10] int top = -1

Here, 10 is a pre-defined capacity of the stack. We can throw a stack overflow error if a user tries to exceed this capacity.

★ The default value for the top is -1, denoting that the stack is empty.

Do we need to store any other parameter for the stack? current size, perhaps? No. We may need to store the capacity of the stack but we don’t need to store the current size. We can know the current size of stack by looking at the value of the top. (How?)

Let us wrap this group of data members in a class

class Stack{ int arr[] int capacity int top }

Let us also create a constructor which initializes capacity and top

Stack(int cap) { capacity = cap top = -1 }

★ You are also required to allocate memory to arr according to the language you use to implement it.

→Now, we need to implement the operations that we generally perform on stacks.

PUSH Operation

What changes are made to the stack when a new element is pushed?

  • A new element is inserted on top
  • The value of top increases by 1

▹ What if the stack is filled to its capacity?

We shall check if the stack if full before inserting a new element and throw an error if it is.

Now, let us implement this simply

void push(int item) { if ( top == capacity - 1 ) print( "Stack overflow!" ) else { arr[top+1] = item top = top + 1 } }
POP Operation

Let’s try one more: Pop().

What changes are made to the stack internally for a pop operation?

  • The top element is removed
  • The value of top is decreased by 1

▹ Can you think of an exception in this case like the one above of stack being full? Ans: The stack can be empty when the pop operation is called

Let’s try implementing it now

void pop() { if ( isEmpty() == True ) print( "Stack is empty!" ) else top = top - 1 }

★ Is decreasing the value of top same as deleting the top element? (Think!)

Peek and isEmpty Operation

Peek and isEmpty are quite simple to implement. We need to steer clear of exceptions though.

int peek() { if ( isEmpty() == True ) { print( "Stack is empty!" ) return -1 } else return arr[top] }bool isEmpty() { if ( top == -1 ) return True else return False }

2. Linked List Implementation

Before implementing stack with a linked list, let us first try to visualize a stack as a linked list. There are two ends of a linked list: head and tail.

Which end do you think should represent the top of the stack? (Think!)

The top of the stack should be represented by head because otherwise, we would not be able to implement the operations of the stack in O(1) time complexity.

Let us assume that we have used class for linked list

class ListNode{ int val ListNode next }

What should an empty stack look like if implemented with a linked list? Ans: Its head will point to NULL

ListNode head = NULL

Is there any benefit to implementing a stack as linked list compared to arrays? Ans: We do not need to mention the size of the stack beforehand.

→ Although, if you want to implement a limit to prevent excess use, you may need to encapsulate the class ListNode inside some other class along with a data member capacity.

class Stack{ int capacity class ListNode{ int val ListNode next } }

We shall be using just using class ListNode below for simplicity.

→Let us move towards stack operations

PUSH Operation

The same properties hold as above with an added benefit that we need not worry about the stack being full

void push(int item) { ListNode temp = ListNode(item) temp.next = head head = temp }
POP Operation

Properties of linked list relaxed us from checking if the stack is full in push operation. Do they provide any relaxation for exceptions in pop operation? No. We still need to check if the stack is empty.

Since the top is represented by the head in this implementation. How do we delete the first element in a linked list?

Simple, we make the second element as the head.

void pop() { if ( head == NULL ) print ( "Stack is empty!" ) else head = head.next }

★ You may be required to deallocate the popped node to avoid memory leak according to your programming language's conventions.

Peek and isEmpty Operation

The implementation of these two operations is pretty simple and straight-forward in the linked list too.

int peek() { if ( head == NULL ) { print ( "Stack is empty!" ) return -1 } else return head.val }bool isEmpty() { if ( head == NULL ) return True else return False }

Augmentations in Stack

You can augment the stack data structure according to your needs. You can implement some extra operations like:-

  • isFull(): tells you if the stack if filled to its capacity
  • The pop operation could return the element being deleted

★ A quite interesting augmentation that has been asked in many interviews asks you to implement a MinStack which holds all properties of a regular stack but also returns the minimum value in the stack. Since all stack operations are expected to be executed in constant time, you need to return the minimum element in the stack in O(1) time complexity.

Applications of Stack Data Structure

  • An "undo" mechanism in text editors
  • Forward and backward feature in web browsers
  • Check for balanced parentheses in an expression
  • Expression evaluation and syntax parsing
  • Backtracking. This is a process when you need to access the most recent data element in a series of elements. Think of a maze - how do you find a way from an entrance to an exit? Once you reach a dead end, you must backtrack. But backtrack to where? to the previous choice point. Therefore, at each choice point, you store on a stack all possible choices. Then backtracking simply means popping a next choice from the stack.
  • We use a stack for the Iterative implementation of several recursive programs like tree traversals, DFS traversal in a graph, etc.
  • For solving several problems in algorithms, we use a stack as the principle data structure with which they organize their information.
  • Memory management: Any modern computer environment uses a stack as the primary memory management model for a running program.

Suggested Problems to solve

  • Find next greater element in an array
  • Min Stack Problem
  • Check for balanced parentheses in an expression
  • Largest Rectangle in a Histogram
  • Trapping Rainwater
  • Reverse a stack using recursion
  • Validate Stack Sequences
  • Merge overlapping intervals
  • Sort a stack using another stack
  • Check if a string is a palindrome using stacks

Happy Coding! Enjoy Algorithms!

AfterAcademy Data Structure And Algorithms Online Course - Admissions Open

Stack Data Structure (Introduction and Program)

Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out).

Mainly the following three basic operations are performed in the stack:

  • Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition.
  • Pop: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be an Underflow condition.
  • Peek or Top: Returns the top element of the stack.
  • isEmpty: Returns true if the stack is empty, else false.

How to understand a stack practically?
There are many real-life examples of a stack. Consider the simple example of plates stacked over one another in a canteen. The plate which is at the top is the first one to be removed, i.e. the plate which has been placed at the bottommost position remains in the stack for the longest period of time. So, it can be simply seen to follow the LIFO/FILO order.

Time Complexities of operations on stack:



push(), pop(), isEmpty() and peek() all take O(1) time. We do not run any loop in any of these operations.

Applications of stack:

  • Balancing of symbols
  • Infix to Postfix /Prefix conversion
  • Redo-undo features at many places like editors, photoshop.
  • Forward and backward feature in web browsers
  • Used in many algorithms like Tower of Hanoi, tree traversals, stock span problem, histogram problem.
  • Backtracking is one of the algorithm designing techniques. Some examples of backtracking are the Knight-Tour problem, N-Queen problem, find your way through a maze, and game-like chess or checkers in all these problems we dive into someway if that way is not efficient we come back to the previous state and go into some another path. To get back from a current state we need to store the previous state for that purpose we need a stack.
  • In Graph Algorithms like Topological Sorting and Strongly Connected Components
  • In Memory management, any modern computer uses a stack as the primary management for a running purpose. Each program that is running in a computer system has its own memory allocations
  • String reversal is also another application of stack. Here one by one each character gets inserted into the stack. So the first character of the string is on the bottom of the stack and the last element of a string is on the top of the stack. After Performing the pop operations on the stack we get a string in reverse order.

Implementation:
There are two ways to implement a stack:

  • Using array
  • Using linked list
Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Implementing Stack using Arrays

C++




/* C++ program to implement basic stack
operations */
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000
class Stack {
int top;
public:
int a[MAX]; // Maximum size of Stack
Stack() { top = -1; }
bool push(int x);
int pop();
int peek();
bool isEmpty();
};
bool Stack::push(int x)
{
if (top >= (MAX - 1)) {
cout << "Stack Overflow";
return false;
}
else {
a[++top] = x;
cout << x << " pushed into stack\n";
return true;
}
}
int Stack::pop()
{
if (top < 0) {
cout << "Stack Underflow";
return 0;
}
else {
int x = a[top--];
return x;
}
}
int Stack::peek()
{
if (top < 0) {
cout << "Stack is Empty";
return 0;
}
else {
int x = a[top];
return x;
}
}
bool Stack::isEmpty()
{
return (top < 0);
}
// Driver program to test above functions
int main()
{
class Stack s;
s.push(10);
s.push(20);
s.push(30);
cout << s.pop() << " Popped from stack\n";
//print all elements in stack :
cout<<"Elements present in stack : ";
while(!s.isEmpty())
{
// print top element in stack
cout<<s.peek()<<" ";
// remove top element in stack
s.pop();
}
return 0;
}
C




// C program for array implementation of stack
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
// A structure to represent a stack
struct Stack {
int top;
unsigned capacity;
int* array;
};
// function to create a stack of given capacity. It initializes size of
// stack as 0
struct Stack* createStack(unsigned capacity)
{
struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
stack->capacity = capacity;
stack->top = -1;
stack->array = (int*)malloc(stack->capacity * sizeof(int));
return stack;
}
// Stack is full when top is equal to the last index
int isFull(struct Stack* stack)
{
return stack->top == stack->capacity - 1;
}
// Stack is empty when top is equal to -1
int isEmpty(struct Stack* stack)
{
return stack->top == -1;
}
// Function to add an item to stack. It increases top by 1
void push(struct Stack* stack, int item)
{
if (isFull(stack))
return;
stack->array[++stack->top] = item;
printf("%d pushed to stack\n", item);
}
// Function to remove an item from stack. It decreases top by 1
int pop(struct Stack* stack)
{
if (isEmpty(stack))
return INT_MIN;
return stack->array[stack->top--];
}
// Function to return the top from stack without removing it
int peek(struct Stack* stack)
{
if (isEmpty(stack))
return INT_MIN;
return stack->array[stack->top];
}
// Driver program to test above functions
int main()
{
struct Stack* stack = createStack(100);
push(stack, 10);
push(stack, 20);
push(stack, 30);
printf("%d popped from stack\n", pop(stack));
return 0;
}
Java




/* Java program to implement basic stack
operations */
class Stack {
static final int MAX = 1000;
int top;
int a[] = new int[MAX]; // Maximum size of Stack
boolean isEmpty()
{
return (top < 0);
}
Stack()
{
top = -1;
}
boolean push(int x)
{
if (top >= (MAX - 1)) {
System.out.println("Stack Overflow");
return false;
}
else {
a[++top] = x;
System.out.println(x + " pushed into stack");
return true;
}
}
int pop()
{
if (top < 0) {
System.out.println("Stack Underflow");
return 0;
}
else {
int x = a[top--];
return x;
}
}
int peek()
{
if (top < 0) {
System.out.println("Stack Underflow");
return 0;
}
else {
int x = a[top];
return x;
}
}
void print(){
for(int i = top;i>-1;i--){
System.out.print(" "+ a[i]);
}
}
}
// Driver code
class Main {
public static void main(String args[])
{
Stack s = new Stack();
s.push(10);
s.push(20);
s.push(30);
System.out.println(s.pop() + " Popped from stack");
System.out.println("Top element is :" + s.peek());
System.out.print("Elements present in stack :");
s.print();
}
}
Python3




# Python program for implementation of stack
# import maxsize from sys module
# Used to return -infinite when stack is empty
from sys import maxsize
# Function to create a stack. It initializes size of stack as 0
def createStack():
stack = []
return stack
# Stack is empty when stack size is 0
def isEmpty(stack):
return len(stack) == 0
# Function to add an item to stack. It increases size by 1
def push(stack, item):
stack.append(item)
print(item + " pushed to stack ")
# Function to remove an item from stack. It decreases size by 1
def pop(stack):
if (isEmpty(stack)):
return str(-maxsize -1) # return minus infinite
return stack.pop()
# Function to return the top from stack without removing it
def peek(stack):
if (isEmpty(stack)):
return str(-maxsize -1) # return minus infinite
return stack[len(stack) - 1]
# Driver program to test above functions
stack = createStack()
push(stack, str(10))
push(stack, str(20))
push(stack, str(30))
print(pop(stack) + " popped from stack")
C#




// C# program to implement basic stack
// operations
using System;
namespace ImplementStack {
class Stack {
private int[] ele;
private int top;
private int max;
public Stack(int size)
{
ele = new int[size]; // Maximum size of Stack
top = -1;
max = size;
}
public void push(int item)
{
if (top == max - 1) {
Console.WriteLine("Stack Overflow");
return;
}
else {
ele[++top] = item;
}
}
public int pop()
{
if (top == -1) {
Console.WriteLine("Stack is Empty");
return -1;
}
else {
Console.WriteLine("{0} popped from stack ", ele[top]);
return ele[top--];
}
}
public int peek()
{
if (top == -1) {
Console.WriteLine("Stack is Empty");
return -1;
}
else {
Console.WriteLine("{0} popped from stack ", ele[top]);
return ele[top];
}
}
public void printStack()
{
if (top == -1) {
Console.WriteLine("Stack is Empty");
return;
}
else {
for (int i = 0; i <= top; i++) {
Console.WriteLine("{0} pushed into stack", ele[i]);
}
}
}
}
// Driver program to test above functions
class Program {
static void Main()
{
Stack p = new Stack(5);
p.push(10);
p.push(20);
p.push(30);
p.printStack();
p.pop();
}
}
}
Javascript




<script>
/* javascript program to implement basic stack
operations
*/
var t = -1;
var MAX = 1000;
var a = Array(MAX).fill(0); // Maximum size of Stack
function isEmpty() {
return (t < 0);
}
function push(x) {
if (t >= (MAX - 1)) {
document.write("Stack Overflow");
return false;
} else {
t+=1;
a[t] = x;
document.write(x + " pushed into stack<br/>");
return true;
}
}
function pop() {
if (t < 0) {
document.write("Stack Underflow");
return 0;
} else {
var x = a[t];
t-=1;
return x;
}
}
function peek() {
if (t < 0) {
document.write("Stack Underflow");
return 0;
} else {
var x = a[t];
return x;
}
}
function print() {
for (i = t; i > -1; i--) {
document.write(" " + a[i]);
}
}
push(10);
push(20);
push(30);
document.write(pop() + " Popped from stack");
document.write("<br/>Top element is :" + peek());
document.write("<br/>Elements present in stack : ");
print();
// This code is contributed by Rajput-Ji
</script>

Output :

10 pushed into stack 20 pushed into stack 30 pushed into stack 30 Popped from stack Top element is : 20 Elements present in stack : 20 10

Pros: Easy to implement. Memory is saved as pointers are not involved.
Cons: It is not dynamic. It doesn’t grow and shrink depending on needs at runtime.
Implementing Stack using Linked List:

C++




// C++ program for linked list implementation of stack
#include <bits/stdc++.h>
using namespace std;
// A structure to represent a stack
class StackNode {
public:
int data;
StackNode* next;
};
StackNode* newNode(int data)
{
StackNode* stackNode = new StackNode();
stackNode->data = data;
stackNode->next = NULL;
return stackNode;
}
int isEmpty(StackNode* root)
{
return !root;
}
void push(StackNode** root, int data)
{
StackNode* stackNode = newNode(data);
stackNode->next = *root;
*root = stackNode;
cout << data << " pushed to stack\n";
}
int pop(StackNode** root)
{
if (isEmpty(*root))
return INT_MIN;
StackNode* temp = *root;
*root = (*root)->next;
int popped = temp->data;
free(temp);
return popped;
}
int peek(StackNode* root)
{
if (isEmpty(root))
return INT_MIN;
return root->data;
}
// Driver code
int main()
{
StackNode* root = NULL;
push(&root, 10);
push(&root, 20);
push(&root, 30);
cout << pop(&root) << " popped from stack\n";
cout << "Top element is " << peek(root) << endl;
cout<<"Elements present in stack : ";
//print all elements in stack :
while(!isEmpty(root))
{
// print top element in stack
cout<<peek(root)<<" ";
// remove top element in stack
pop(&root);
}
return 0;
}
// This is code is contributed by rathbhupendra
C




// C program for linked list implementation of stack
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
// A structure to represent a stack
struct StackNode {
int data;
struct StackNode* next;
};
struct StackNode* newNode(int data)
{
struct StackNode* stackNode =
(struct StackNode*)
malloc(sizeof(struct StackNode));
stackNode->data = data;
stackNode->next = NULL;
return stackNode;
}
int isEmpty(struct StackNode* root)
{
return !root;
}
void push(struct StackNode** root, int data)
{
struct StackNode* stackNode = newNode(data);
stackNode->next = *root;
*root = stackNode;
printf("%d pushed to stack\n", data);
}
int pop(struct StackNode** root)
{
if (isEmpty(*root))
return INT_MIN;
struct StackNode* temp = *root;
*root = (*root)->next;
int popped = temp->data;
free(temp);
return popped;
}
int peek(struct StackNode* root)
{
if (isEmpty(root))
return INT_MIN;
return root->data;
}
int main()
{
struct StackNode* root = NULL;
push(&root, 10);
push(&root, 20);
push(&root, 30);
printf("%d popped from stack\n", pop(&root));
printf("Top element is %d\n", peek(root));
return 0;
}
Java




// Java Code for Linked List Implementation
public class StackAsLinkedList {
StackNode root;
static class StackNode {
int data;
StackNode next;
StackNode(int data) { this.data = data; }
}
public boolean isEmpty()
{
if (root == null) {
return true;
}
else
return false;
}
public void push(int data)
{
StackNode newNode = new StackNode(data);
if (root == null) {
root = newNode;
}
else {
StackNode temp = root;
root = newNode;
newNode.next = temp;
}
System.out.println(data + " pushed to stack");
}
public int pop()
{
int popped = Integer.MIN_VALUE;
if (root == null) {
System.out.println("Stack is Empty");
}
else {
popped = root.data;
root = root.next;
}
return popped;
}
public int peek()
{
if (root == null) {
System.out.println("Stack is empty");
return Integer.MIN_VALUE;
}
else {
return root.data;
}
}
// Driver code
public static void main(String[] args)
{
StackAsLinkedList sll = new StackAsLinkedList();
sll.push(10);
sll.push(20);
sll.push(30);
System.out.println(sll.pop()
+ " popped from stack");
System.out.println("Top element is " + sll.peek());
}
}
Python3




# Python program for linked list implementation of stack
# Class to represent a node
class StackNode:
# Constructor to initialize a node
def __init__(self, data):
self.data = data
self.next = None
class Stack:
# Constructor to initialize the root of linked list
def __init__(self):
self.root = None
def isEmpty(self):
return True if self.root is None else False
def push(self, data):
newNode = StackNode(data)
newNode.next = self.root
self.root = newNode
print ("% d pushed to stack" % (data))
def pop(self):
if (self.isEmpty()):
return float("-inf")
temp = self.root
self.root = self.root.next
popped = temp.data
return popped
def peek(self):
if self.isEmpty():
return float("-inf")
return self.root.data
# Driver code
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)
print ("% d popped from stack" % (stack.pop()))
print ("Top element is % d " % (stack.peek()))
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
C#




// C# Code for Linked List Implementation
using System;
public class StackAsLinkedList {
StackNode root;
public class StackNode {
public int data;
public StackNode next;
public StackNode(int data) { this.data = data; }
}
public bool isEmpty()
{
if (root == null) {
return true;
}
else
return false;
}
public void push(int data)
{
StackNode newNode = new StackNode(data);
if (root == null) {
root = newNode;
}
else {
StackNode temp = root;
root = newNode;
newNode.next = temp;
}
Console.WriteLine(data + " pushed to stack");
}
public int pop()
{
int popped = int.MinValue;
if (root == null) {
Console.WriteLine("Stack is Empty");
}
else {
popped = root.data;
root = root.next;
}
return popped;
}
public int peek()
{
if (root == null) {
Console.WriteLine("Stack is empty");
return int.MinValue;
}
else {
return root.data;
}
}
// Driver code
public static void Main(String[] args)
{
StackAsLinkedList sll = new StackAsLinkedList();
sll.push(10);
sll.push(20);
sll.push(30);
Console.WriteLine(sll.pop() + " popped from stack");
Console.WriteLine("Top element is " + sll.peek());
}
}
/* This code contributed by PrinciRaj1992 */
Javascript




<script>
// javascript Code for Linked List Implementation
var root;
class StackNode {
constructor(data) {
this.data = data;
this.next = null;
}
}
function isEmpty() {
if (root == null) {
return true;
} else
return false;
}
function push(data) {
var newNode = new StackNode(data);
if (root == null) {
root = newNode;
} else {
var temp = root;
root = newNode;
newNode.next = temp;
}
document.write(data + " pushed to stack<br/>");
}
function pop() {
var popped = Number.MIN_VALUE;
if (root == null) {
document.write("Stack is Empty");
} else {
popped = root.data;
root = root.next;
}
return popped;
}
function peek() {
if (root == null) {
document.write("Stack is empty");
return Number.MIN_VALUE;
} else {
return root.data;
}
}
// Driver code
push(10);
push(20);
push(30);
document.write(pop() + " popped from stack<br/>");
document.write("Top element is " + peek());
// This code is contributed by Rajput-Ji
</script>

Output:

10 pushed to stack 20 pushed to stack 30 pushed to stack 30 popped from stack Top element is 20 Elements present in stack : 20 10

Pros: The linked list implementation of a stack can grow and shrink according to the needs at runtime.
Cons: Requires extra memory due to involvement of pointers.

//youtu.be/vZEuSFXSMDI

We will cover the implementation of applications of the stack in separate posts.

Stack Set -2 (Infix to Postfix)

Quiz: Stack Questions

References:
//en.wikipedia.org/wiki/Stack_%28abstract_data_type%29#Problem_Description

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.




Article Tags :
Arrays
Linked List
Stack
Codenation
FactSet
Goldman Sachs
Kritikal Solutions
Microsoft
Qualcomm
Samsung
Visa
Practice Tags :
Microsoft
Samsung
FactSet
Visa
Goldman Sachs
Qualcomm
Codenation
Kritikal Solutions
Linked List
Arrays
Stack
Read Full Article

stack top() in C++ STL

Stacks are a type of container adaptors with LIFO(Last In First Out) type of work, where a new element is added at one end called the top of the stack, and an element is removed from the same end only.

stack::top() top() function is used to reference the top(or the newest) element of the stack.

Syntax :

stackname.top()

Parameters: No value is needed to pass as the parameter.
Return Value: Direct reference to the top element of the stack container.

Examples:



Input : stackname.push(5); stackname.push(1); stackname.top(); Output : 1 Input : stackname.push(5); stackname.push(1); stackname.push(2); stackname.top(); Output : 2

Errors and Exceptions

  1. If the stack container is empty, it causes undefined behavior
  2. It has a no exception throw guarantee if the stack is not empty
C++




// CPP program to illustrate
// Implementation of top() function
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int> mystack;
mystack.push(5);
mystack.push(1);
mystack.push(2);
// Stack top
cout << mystack.top();
return 0;
}

Output:

2

Application :
Given a stack of integers, find the sum of the all the integers.

Input : 1, 8, 3, 6, 2 Output: 20

Algorithm

  1. Check if the stack is empty, if not add the top element to a variable initialized as 0, and pop the top element.
  2. Repeat this step until the stack is empty.
  3. Print the final value of the variable.
C++




// CPP program to illustrate
// Application of top() function
#include <iostream>
#include <stack>
using namespace std;
int main()
{
int sum = 0;
stack<int> mystack;
mystack.push(1);
mystack.push(8);
mystack.push(3);
mystack.push(6);
mystack.push(2);
// Stack becomes 1, 8, 3, 6, 2
while (!mystack.empty()) {
sum = sum + mystack.top();
mystack.pop();
}
cout << sum;
return 0;
}

Output:

20
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.



Article Tags :
C++
cpp-containers-library
CPP-Library
cpp-stack
cpp-stack-functions
STL
Practice Tags :
STL
CPP
Read Full Article

Sample Tutorial Problem

Nainital is a Himalayan resort town in the Kumaon region of India s Uttarakhand state, at an elevation of roughly 2,000m. A group of students from a reputed college went there for an educational tour. They went there for performing some experiment regarding their project. Each student is placed on each different hill point of each hill with a modulation machine.

Suppose all machines are aligned in a straight horizontal line from left to right and each machine transmits a signal in the right to left direction. Machine A shall block the signal of machine B if machine A is present to the left of machine B and machine A is taller than machine B. So, the range of a signal of a given machine can be defined as : the number of contiguous machines just to the left of the given machine whose height is less than or equal to the height of the given machine + 1. You need to find the range of each machine.


Input Format

Input 1: It will be an integer N specifying the number of machines where 2 <= N <= 10^6

Input 2: It will be a string denoting N comma separated integers(H[i]) denoting the height of each machine where 1 <= H[i] <= 10^8.


Output Format

It will be an integer which tells the range of each machine (separated by a comma).


Sample TestCase 1Input7 100,80,60,70,60,75,85Output1,1,1,2,1,4,6
×

Which section of Tutorial Needs Improvement

Quality of Tutorial Depth of Tutorial

Any Other

Send Feedback

Video liên quan

Postingan terbaru

LIHAT SEMUA