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

What Is Stack

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

What Is Stack

CSE
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

What is Stack?

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). LIFO implies that the element that is
inserted last, comes out first and FILO implies that the element that is inserted first, comes out last.
There are many real-life examples of a stack. Consider an example of plates stacked over one
another in the 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 LIFO(Last In First Out)/FILO(First In Last Out) order.

uses of stack:
1.Plate Stacking: Placing clean plates on a stack, and taking the top one when needed.

2.Book Stacking: Adding books to a pile, and taking the top book for reading.

3.Pancake Making: Adding layers to a pancake stack, with the top layer being the first one
consumed.

4.Luggage Packing: Placing suitcases in a car trunk, with the last one in being the first one out.

5.Cash Register Operations: Processing items in a retail setting, where the last item scanned is
the first processed.

6.Browser History: Navigating web pages with back and forward buttons, similar to a stack.

7.Checkout Lines: Joining a line in a supermarket, with the last person joining being the first
served.

8.Trays in a Cafeteria: Taking the top tray from a stack.

9.Pringles Chips Packaging: Chips are stacked in a container, with the last chip placed being
the first accessed.

10.Paper Trays in a Printer: The printer pulls paper from the top tray first.

11.Queue at a Ticket Counter: The last person to join is usually the first to get a ticket.

12.Stacking Blocks or Toys: Children stack items, with the last one placed being the first
removed.
Advantages of Stack:

The advantages of using stack are listed below:

1. Efficient data management: Stack helps you manage the data in a LIFO (last in, first out)
method, which is not possible with a Linked list and array.
2. Efficient management of functions: When a function is called, the local variables are
stored in a stack, and it is automatically destroyed once returned.
3. Control over memory: Stack allows you to control how memory is allocated and
deallocated.
4. Smart memory management: Stack automatically cleans up the object.
5. Not easily corrupted: Stack does not get corrupted easily; hence it is more secure and
reliable.
6. Does not allow resizing of variables: Variables cannot be resized.

The disadvantages of using stack :

1.Limited memory size: Stack memory is very limited.

2.Chances of stack overflow: Creating too many objects on the stack can increase the risk
of stack overflow.

3.Random access is not possible: In a stack, random accessing the data is not possible.

4.Unreliable: When variable storage will get overwritten, it will sometimes leads to
undefined behaviour of the function or program.

5.Undesired termination: The stack will fall outside of the memory area, which might lead
to an abnormal termination.

Implementation of stack:
1.stack using array:
#include<stdio.h>

#define CAPACITY 3

int stack[CAPACITY];

int top=-1;

void push(int x)

{
if(top<CAPACITY-1)

top=top+1;

stack[top]=x;

printf("%d\n",x);

int pop()

if(top>=0)

int val=stack[top];

top=top-1;

return val;

return -1;

int peek()

if(top>=0)

return stack[top];

return -1;

}
int main()

push(10);

push(20);

push(30);

printf("peek is:%d\n",peek());

printf("pop:%d\n",pop());

printf("peek:%d",peek());

stack using linklist:


#include<stdio.h>

#include<stdlib.h>

struct node

int data;

struct node *link;

};

struct node *top=0,*newnode;

void push(int x)

newnode=(struct node*)malloc(sizeof(struct node));

newnode->data=x;

newnode->link=top;

top=newnode;

}
void display()

struct node *temp;

temp=top;

if(top==0)

printf("empty");

else

while(temp!=0)

printf("%d\n",temp->data);

temp=temp->link;

void peek()

if(top==0)

printf("empty");

else

printf("top element is %d\n",top->data);

void pop()
{

struct node *temp;

temp=top;

if(top==0)

printf("underflow");

else

printf("%d\n",top->data);

top=top->link;

free(temp);

void main()

push(2);

push(3);

push(10);

display();

peek();

pop();

peek();

display();

}
Algoritm of a stack:
Algorithm for Stack using Linked List:

1. Define a structure for a stack node:

- struct Node {

int data; // Data of the node

struct Node* link; // Pointer to the next node

2. Initialize the stack:

- Create a global pointer 'top' and set it to NULL to indicate an empty stack.

3. Push operation:

- Create a new node 'newnode' using dynamic memory allocation (malloc).

- Set the data of 'newnode' to the input value 'x'.

- Set the link of 'newnode' to point to the current top of the stack.

- Update 'top' to point to 'newnode'.

4. Pop operation:

- Check if the stack is not empty (top is not NULL).

- If true, create a temporary pointer 'temp' and set it to 'top'.

- Print the data of the top node.

- Update 'top' to point to the next node.

- Free the memory of 'temp'.

5. Peek operation:
- Check if the stack is not empty (top is not NULL).

- If true, print the data of the top node.

6. Display operation:

- Create a temporary pointer 'temp' and set it to 'top'.

- If 'top' is NULL, print "empty".

- Otherwise, while 'temp' is not NULL, print the data of 'temp', then update 'temp' to point to the next node.

7. Main function:

- Initialize the stack in the main function.

- Perform push, pop, peek, and display operations as needed.

8. Memory management:

- Ensure that memory allocated for each node is properly freed using 'free' to avoid memory leaks.

9. Error handling:

- Implement mechanisms to handle cases of stack underflow (e.g., printing "underflow") or empty stack (e.g.,
printing "empty").

10. Remember to handle special cases:

- Consider edge cases, such as pushing to an empty stack or popping from an empty stack, and handle them
appropriately.

Algorithm for Stack using Array

1. Define a global array 'stack' and an integer 'top' initialized to -1.

2. Push operation:

- Check if the stack is not full (top < CAPACITY - 1).


- If true, increment 'top' by 1.

- Set stack[top] to the input value 'x'.

3. Pop operation:

- Check if the stack is not empty (top >= 0).

- If true, retrieve the element from stack[top].

- Decrement 'top' by 1.

- Return the retrieved element.

- If false, indicate stack underflow.

4. Peek operation:

- Check if the stack is not empty (top >= 0).

- If true, return stack[top].

- If false, indicate an empty stack.

5. Display operation:

- Start a loop from 'i' = 0 to 'i' = top:

- Print stack[i].

6. Main function:

- Initialize 'top' to -1.

- Perform push, pop, peek, and display operations as needed.

7. Memory management:

- No dynamic memory allocation needed, as the stack is implemented using a fixed-size array.

8. Error handling:
- Implement mechanisms to handle cases of stack overflow (e.g., printing "Stack Overflow") or empty stack (e.g.,
printing "Stack Underflow").

9. Remember to handle special cases:

- Consider edge cases, such as pushing to a full stack or popping from an empty stack, and handle them
appropriately.

senario for stack:


Some Applications of a stack are:
 Converting infix to postfix expressions.
 Undo/Redo button/operation in word processors.
 Syntaxes in languages are parsed using stacks.
 It is used in many virtual machines like JVM.
 Forward-backward surfing in the browser.
 History of visited websites.
 Message logs and all messages you get are arranged in a stack.
 Call logs, E-mails, Google photos’ any gallery, YouTube downloads, Notifications (
latest appears first ).
 Scratch card’s earned after Google pay transaction.
 Wearing/Removing Bangles, Pile of Dinner Plates, Stacked chairs.
 Changing wearables on a cold evening, first in, comes out at last.
 Last Hired, First Fired - which is typically utilized when a company reduces its workforce
in an economic recession.
 Loading bullets into the magazine of a gun. The last one to go in is fired first. Bam!
 Java Virtual Machine.
 Recursion.
 Used in IDEs to check for proper parentheses matching
 Media playlist. T o play previous and next song

Difference between Stack and Queue Data Structures are as follows:


Stacks Queues

A stack is a data structure that stores a A queue is a data structure that stores a collection
collection of elements, with operations of elements, with operations to enqueue (add)
to push (add) and pop (remove) elements at the back of the queue, and dequeue
elements from the top of the stack. (remove) elements from the front of the queue.

Stacks are based on the LIFO Queues are based on the FIFO principle, i.e., the
Stacks Queues

principle, i.e., the element inserted at element inserted at the first, is the first element to
the last, is the first element to come come out of the list.
out of the list.

Stacks are often used for tasks that


Queues are often used for tasks that involve
require backtracking, such as parsing
processing elements in a specific order, such as
expressions or implementing undo
handling requests or scheduling tasks.
functionality.

Insertion and deletion in queues takes place from


Insertion and deletion in stacks takes
the opposite ends of the list. The insertion takes
place only from one end of the list
place at the rear of the list and the deletion takes
called the top.
place from the front of the list.

Insert operation is called push


Insert operation is called enqueue operation.
operation.

Stacks are implemented using an array Queues are implemented using an array or linked
or linked list data structure. list data structure.

Delete operation is called pop


Delete operation is called dequeue operation.
operation.

In queues we maintain two pointers to access the


In stacks we maintain only one pointer
list. The front pointer always points to the first
to access the list, called the top, which
element inserted in the list and is still present, and
always points to the last element
the rear pointer always points to the last inserted
present in the list.
element.

Stack is used in solving problems Queue is used in solving problems having


works on recursion. sequential processing.

Stacks are often used for recursive Queues are often used in multithreaded
algorithms or for maintaining a history applications, where tasks are added to a queue and
of function calls. executed by a pool of worker threads.

Queue is of three types – 1. Circular Queue 2.


Stack does not have any types.
Priority queue 3. double-ended queue.
Stacks Queues

Can be considered as a vertical Can be considered as a horizontal collection


collection visual. visual.

Examples of queue-based algorithms include


Examples of stack-based languages
Breadth-First Search (BFS) and printing a binary
include PostScript and Forth.
tree level-by-level.

where we use stack and where we use quieue:


Stacks are beneficial when:

Last-In, First-Out (LIFO) Behavior is Required:


 Situations where the most recently added item needs to be processed first are better
suited for a stack.
Undo and Redo Functionality is Needed:
 Stacks are great for implementing undo and redo operations in applications.
Depth-First Search (DFS) or Backtracking is Involved:
 Algorithms like DFS often rely on a stack to efficiently explore solution spaces.
Expression Parsing and Evaluation is Required:
 Converting infix expressions to postfix or prefix form and evaluating them is facilitated
by using a stack.
Balancing Parentheses and Brackets is Critical:
 Ensuring that parentheses, brackets, and braces are properly balanced in code can be
efficiently done using a stack.

Queues are beneficial when:

First-In, First-Out (FIFO) Behavior is Required:


 Situations where the oldest item needs to be processed first are better suited for a
queue.
Breadth-First Search (BFS) is Involved:
 Algorithms like BFS in graph traversal require a queue to explore nodes at the current
level before moving to the next level.
Handling Task Scheduling:
 Managing tasks or processes that arrive sequentially and need to be processed in order
is often done using a queue.
Buffering and Buffer Management:
In scenarios where data arrives continuously and needs to be processed in a controlled

manner, a queue is more appropriate.
Handling Waiting Lines or Service Requests:
 Situations where customers or requests are served on a first-come, first-served basis are
best managed with a queue.

We convert a code quieue to stack :


this is queie code:
#include<stdio.h>

#include<stdlib.h>

struct node

int data;

struct node *next;

};

struct node *front=0;

struct node *rear=0;

void enqueue(int x)

struct node *newnode;

newnode=(struct node*)malloc(sizeof(struct node));

newnode->data=x;

newnode->next=0;

if(front==0 && rear==0)

front=rear=newnode;

else

rear->next=newnode;
rear=newnode;

void display()

struct node *temp;

if(front==0&&rear==0)

printf("empty");

else

temp=front;

while(temp!=0)

printf("%d\n",temp->data);

temp=temp->next;

void dequeue()

struct node *temp;

temp=front;

if(front==0&&rear==0)

printf("empty");

else
{

printf("%d\n",front->data);

front=front->next;

free(temp);

void peek()

if(front==0&&rear==0)

printf("empty");

else

printf("%d\n",front->data);

void main()

enqueue(5);

enqueue(0);

enqueue(-3);

display();

peek();

converted code:
#include<stdio.h>

#include<stdlib.h>

struct node

int data;

struct node *next;


};

struct node *top = 0; // Change 'front' and 'rear' to 'top'.

void push(int x) // Change 'enqueue' to 'push'.

struct node *newnode;

newnode = (struct node*)malloc(sizeof(struct node));

newnode->data = x;

newnode->next = top; // Change 'rear' to 'top'.

top = newnode; // Change 'rear' to 'top'.

void display()

struct node *temp;

if(top == 0) // Change 'front' and 'rear' to 'top'.

printf("empty");

else

temp = top; // Change 'front' and 'rear' to 'top'.

while(temp != 0)

printf("%d\n",temp->data);

temp = temp->next;

}
void pop() // Change 'dequeue' to 'pop'.

struct node *temp;

temp = top; // Change 'front' and 'rear' to 'top'.

if(top == 0) // Change 'front' and 'rear' to 'top'.

printf("empty");

else

printf("%d\n",top->data); // Change 'front' to 'top'.

top = top->next; // Change 'front' to 'top'.

free(temp);

void peek()

if(top == 0) // Change 'front' and 'rear' to 'top'.

printf("empty");

else

printf("%d\n",top->data); // Change 'front' to 'top'.

void main()

push(5); // Change 'enqueue' to 'push'.

push(0); // Change 'enqueue' to 'push'.

push(-3); // Change 'enqueue' to 'push'.

display();

peek();
}

You might also like