0% found this document useful (0 votes)
13 views

Stacks and Applications

Uploaded by

Faizan Ahmad
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Stacks and Applications

Uploaded by

Faizan Ahmad
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Stack & Applications

Dr. Subhash Chandra


Gupta
Assistant Professor
Today’s discussion…
Stack
*Basic principles
*Operation of stack
*Stack using Array
*Stack using Linked List
*Applications of stack
Basic Idea
• A stack is an Abstract Data Type (ADT), commonly used in most
programming languages. It is named stack as it behaves like a real-world
stack, for example – a deck of cards or a pile of plates, etc.
Stack Representation

• Can be implemented by means of Array, Structure, Pointers and Linked List.


• Stack can either be a fixed size or dynamic.
push

pop

create
STACK
isempty

isfull
STACK: Last-In-First-Out (LIFO)
• void push (stack *s, int element);
/* Insert an element in the stack */
• int pop (stack *s);
/* Remove and return the top element */
• void create (stack *s);
/* Create a new stack */
• int isempty (stack *s);
/* Check if stack is empty */
• int isfull (stack *s);
/* Check if stack is full */

Assumption: stack contains integer elements!


Stack using Array
Push using Stack

PUSH

top
top
Pop using Stack

POP

top
top
Stack using Linked List
Push using Linked List

PUSH OPERATION

top
Pop using Linked List

POP OPERATION

top
Basic Idea
• In the array implementation, we would:

• Declare an array of fixed size (which determines the maximum size of the
stack)
• Keep a variable which always points to the “top” of the stack.
• Contains the array index of the “top” element.

• In the linked list implementation, we would:

• Maintain the stack as a linked list.


• A pointer variable top points to the start of the list.
• The first element of the linked list is considered as the stack top.
Declaration & Creation
class Node
#define MAX 1000
{
public:
class Stack {
int data;
int top;
Node* link;
// Constructor
public:
Node(int n)
int a[MAX];
{
Stack() { top = -1; }
this->data = n;
bool push(int x);
this->link =
int pop();
NULL;
int peek();
}
bool isEmpty();
Stack() { top=NULL; }
};
};

ARRAY LINKED LIST


Pushing an element into stack
bool push(int x) void push(int data)
{ {
if (top >= (MAX - 1)) Node* temp = new Node(data);
{ // Check if stack (heap) is full.
cout << "Stack Overflow";
return false; if (!temp)
{
}
cout << "\nStack Overflow";
else exit(1);
{ }
a[++top] = x;
cout << x << " pushed into temp->data = data;
stack\n"; temp->link = top;
return true; top = temp;
} }
}

ARRAY LINKED LIST


Popping an element from stack
int pop() void pop()
{ {
if (top < 0) Node* temp;
{
cout << "Stack if (top == NULL)
Underflow"; {
return 0; cout << "\nStack Underflow"
} << endl;
else exit(1);
{ }
int x = a[top--]; else
return x; {
} temp = top;
} top = top->link;
free(temp);
}
ARRAY }
LINKED LIST
Checking for stack empty

bool isEmpty () bool isEmpty ()


{ {
return (top<0); return (top==NULL);
} }

ARRAY LINKED LIST


Checking for peek
int peek()
{
if (top < 0) int peek()
{ {
cout << "Stack is // If stack is not empty ,
Empty"; // return the top element
return 0;
} if (!isEmpty())
else return top->data;
{ else
int x = a[top]; exit(1);
return x; }
}
}

ARRAY LINKED LIST


#include <stdio.h>
#define MAXSIZE 100
int main()
{
class Stack s;
s.push(10); Example: A Stack
s.push(20);
s.push(30); using an Array
cout << s.pop() << " Popped from stack\n";

//print top element of stack after poping


cout << "Top element is : " << s.peek() <<
endl;

//print all elements in stack :


cout <<"Elements present in stack : ";
while(!s.isEmpty())
{
// print top element in stack
cout << s.peek() <<" ";
// remove top element from stack
s.pop();
}
return 0;
}
int main()
{
// Creating a stack
Example: A Stack
void display()
{
Stack s; using Linked List
Node* temp;
// Check for stack
// Push the elements of stack
s.push(11); underflow
s.push(22); if (top == NULL)
{
s.push(33);
cout << "\nStack
s.push(44); Underflow";
// Display stack elements exit(1);
s.display(); }
// Print top element of stack else
cout << "\nTop element is " << s.peek() {
<< endl; temp = top;
// Delete top elements of stack while (temp !=
s.pop(); NULL)
{
s.pop();
cout <<
// Display stack elements temp->data;
s.display(); temp =
// Print top element of stack temp->link;
cout << "\nTop element is " << s.peek() << if (temp !=
endl; NULL)
return 0; cout
Complexity Analysis
Time Complexity

Operations Complexity

push() O(1)

pop() O(1)

isEmpty() O(1)

size() O(1)
Stack in C++ STL
Stack-Pair in STL
 Stack in STL Stacks are a type of container adaptors with LIFO(Last In First Out)
type of working, where a new element is added at one end and (top) an element
is removed from that end only.

 Pair in STL The pair container is a simple container defined in header consisting of
two data elements or objects. The first element is referenced as ‘first’ and the
second element as ‘second’ and the order is fixed (first, second).
Design a stack that supports getMin() in O(1) time and O(1)
extra space
int mini(int a, int b) { return a > b ? b : a; }

class MinStack {
public:
stack<pair<int, int> > s;

void push(int element) {


/* new min will be given element, if stack is empty, else we
compare given element to min at current top of stack*/

int new_min = s.empty()? element: mini(element,


s.top().second);

// we push the pair of given_element,new_min in s


s.push({ element, new_min });
}
int pop() {
int popped; // Driver code
if (!s.empty()) { int main()
// popped has popped number {
popped = s.top().first; MinStack s;
s.pop();
} // Function calls
else { s.push(-1);
// print a message or throw exception etc s.push(10);
} s.push(-4);
return popped; s.push(0);
} cout << s.minimum() << endl;
cout << s.pop() << endl;
cout << s.pop() << endl;
int minimum() { cout << s.minimum();
int min_elem = s.top().second; return 0;
return min_elem; }
}
};
Applications of Stacks
• Page-visited history in a Web browser
• Undo sequence in a text editor
• Chain of method calls in the Java Virtual Machine
• Function-call abstraction
• Validate XML
• Auxiliary data structure for algorithms
• Evaluation of Arithmetic expressions
• Polish Notation conversion
• To manage the Symbol table in compile design.
• Balanced Parenthesis in arithmetic expressions.
What is stack size estimation❓

Stack size estimation is process of determining the amount of memory allocated to the call stack for a particular
program or thread. The call stack is a region of memory that operates on a Last In, First Out (LIFO) basis and is
used for managing function calls and local variables.

Here are some key points related to stack size estimation:


 Function Calls: Each time a function is called, a new stack frame is created, which includes space for local variables,
return addresses, and other information related to the function call.

 Recursion: Recursive functions can lead to a significant increase in the stack size, as each recursive call adds a new
stack frame. The depth of recursion directly impacts the stack size required.

 Local Variables: The size of local variables within functions contributes to the overall stack size. Larger local variables or
arrays can consume more stack space.

 Thread Stack Size: In a multithreaded program, each thread typically has its own stack. The stack size for each thread is
specified during thread creation. Estimating the required stack size is crucial to prevent stack
overflow.

 Operating System Limits: Operating systems often impose limits on the maximum stack size for a thread. Exceeding
these limits can result in a stack overflow, leading to program termination.

 Static Analysis and Tools: Some programming languages provide static analysis tools that can estimate the stack size
requirements based on the code structure and function calls.

 Platform and Compiler Considerations: Stack size can vary across different platforms and compilers. It's important for
Any question?

You might also like