0% found this document useful (0 votes)
6 views26 pages

Stack Implementation: Array vs Linked List

Stacks and array for kids
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views26 pages

Stack Implementation: Array vs Linked List

Stacks and array for kids
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

STAC

K Data
Structure
Whatis a STACK
? A stack is a container of elements that are
inserted and removed according to the last-in
first-out (LIFO) principle.

A stack is a ordered list of elements of same data


type

A stack is a Linear list


Whatis a STACK
?
In a stack all
operation like
insertion and deletion
0 1 2 3 4
are performed at
only one end called
Top
Whatis a STACK
? Insertio Deletio
n n

In a stack all 4 To
p
operation like
insertion and deletion 3
are performed at 2
only one end called
1
Top
0
STACK ADT
□ TOP pointer It will always point to the last element inserted in the stack.
For empty stack, top will be pointing to -1 (TOP = -1)
□ PUSH: It is the process of inserting a new element at the Top of the stack
□ POP: It is the process of deleting the Top element of the stack
□ PEEK: Viewing the Nth element from the TOP of the stack
□ TRAVERSE: Visiting elements from position from TOP to 0
□ Stack Overflow: An Attempt to insert an element X when the stack is Full,
is said to be stack overflow
□ Stack Underflow: An Attempt to delete an element when the stack is
empty, is said to be stack underflow
Stack Operations using
array
Algorithm for Push
Operation
Step 1 − IF TOP=MAX-1
PRINT
“OVERFLOW

” GOTO

STEP 4

[END OF IF]
Step 2 − SET TOP=TOP+1
Step 3 − SET
STACK[TOP]=VALUE
Algorithm for
POP
Operati
It is the process of deleting the Top element of the stack
on
It takes only one parameter Pop(X). The element X to be deleted
of the Stack. Before deleting the Top element of the stack,
from the Top
check for Empty Stack

If the Stack is Empty, deletion is not possible.


Otherwise, delete the Top element from the Stack & then
decrement the Top pointer by 1
Algorithm for
POP Operation
Step 1: IF TOP=NULL
PRINT “UNDERFLOW”
GOTO STEP 4
[END OF IF]
Step 2: SET
VAL=STACK[TOP]
Step 3: SET TOP=TOP-1
Step 4: END
Routine for different
operations on
Creatio STACK using array
n

Insertion

Deletion
Operations
on STACK ?
#define 4
Creatio
SIZE
n 5 int 3
Insertio
n stack[SIZE]; 2
Deletio
n 1
Displayin
g 0
stac
k
Operations on
STACK ? Insertion operation is called
as “push”
void 4
Creatio
push(element)
n { 3
Insertio if(Top=MAX-1)
n {
2
Deletio printf(“FULL!!!”);
n 1
}
Displayin else
0
g {
Top++; stack[Top] = stac
element; k
Operations on
STACK ? Deletion operation is called
“p o p ”
as i n t p op( ){ 4
Creatio if(Top==-1)
n { 3
Insertio printf(“EMPTY!!!
n ”); return Top; 2
Deletio }
n else 1
Displayin {
deleted = 0
g
stack[Top]; Top--;
stac
return deleted; k
Operations
on STACK ? void display( 4
Creatio ){
if(Top==- 1)
n 3
Insertio {
printf(“EMPTY!!!”); 2
n }
Deletio else
n {
1
Displayin for(i=Top; i>-1; i--)
0
g printf(“%d\n”,stack[i
]); stac
} k
Algorithm for
Stack
Eopme
Initially Stack is
n
pratytio
With Empty stack TOP pointer points to –1
Empty

It is necessary to check for Empty Stack before deleting (pop) an element


from the stack

Routine to check whether stack is


empty
int IsEmpty ( Stack S ) {
if( Top = = - 1 )

return(1);
}
Aoplgeorraitiom for

F
Stack u l l
As we kee p ins e rting the elements, the Stack
the eleme
gets filled nwith
nts With Full stack TOP pointer points to N–1

where N is the size of the stack

• Hence it is necessary to check whether the stack is full


or not before inserting a
• new element into the stack

• Routine to check whether a stack is full


int IsFull ( Stack S ) { if( Top = = Arraysize – 1 )

return(1);
More
o n
Operations
PEEK (Stack, i) – PEE K re tur ns S at the i location from the
the value th

TOP of the Stack. The element can only be viewed. It cannot be deleted
ta ck
TRAVERSE (Stack) – TRAVERSE is the process of visiting each and every data
inside the data structure only once. In case of Stack from TOP (index of recently
added data) to 0th index RETURNTOP (Stack) – Returns the Topmost element of
Stack
Algorithm for Peek Operation

Step 1: IF TOP=NULL

PRINT “STACK IS
EMPTY” GOTO STEP 3
Step 2: RETURN STACK[TOP]
Stack using
array-Animation
Stack using Linked
List
• A linked list supports all the 3 operations: Push,
Pop & Peek
• PUSH OPERATION:
• The push operation is used to insert an element into
the stack.
• The new element is added at the top most position
of the stack.
(Contd)

•ALGORIT
• HM:
Step 1: Allocate memory for the new node &
name it as NEW_NODE.
• Step 2: SET NEW_NODE->DATA=VAL
• Step 3: IF TOP=NULL
• SET NEW_NODE->NEXT=NULL
• SET TOP=NEW_NODE
• ELSE
• SET NEW_NODE->NEXT=TOP
• SET TOP=NEW_NODE
• [END OF IF]
• Step 4: END
(Contd)

…Explanation:
• In step 1, memory is allocated for the new node.

• In step 2, the DATA part of the new node is initialized with the value to be stored in
the node.
• In step 3, we check if the new node is the first node of the linked list . This is done by
checking if TOP=NULL.

• In case, the IF statement evaluates to true, the NULL is stored in the NEXT part of the
node and the new node is called TOP.

• However, if the new node is not the 1st node in the list, then it is added before the 1st
of the list(ie;the top node) & termed as TOP.
Algorithm for POP operation
using
• The pop operation is used to delete theLinked Listfrom a stack.
top most element
• However, before deleting the value, we must 1st check if TOP=NULL, because
if this is the case, then it means that the stack is empty, and no more
deletions can be done.
• If an attempt is made to delete a value from a stack that is already empty,
an “UNDERFLOW” message is printed.
(Contd)

• ALGORITHM:

• Step 1: IF TOP=NULL
• PRINT
“UNDERFLOW”
• Goto Step 5
• [END OF IF]
• Step 2: SET PTR=TOP
• Step 3: SET TOP=TOP-
>NEXT
• Step 4: FREE PTR
• Step 5: END
(Contd)

• Explanation:

• In step1, we 1st check for the “UNDERFLOW” condition.

• In step 2, we use a pointer PTR that points to TOP.

• In step 3, TOP is made to point to the next node in


sequence.

• In step 4, the memory is occupied by PTR is given back


to the free pool.
Application
s of Stack
The following are some of the applications
of stack:
1. Conversion of Infix to Postfix
Expression
2. Evaluating the Postfix Expression
3. Balancing the Symbols
4. Function Call
5. Tower of Hanoi
6. 8 Queen Problem
7. Recursion

Common questions

Powered by AI

The TOP pointer in stack operations serves as an indicator of the current position of the top element within the stack. For an array-based stack, it helps prevent overflow by ensuring it does not exceed MAX-1 before a push and avoids underflow by checking it is not -1 before a pop . In linked list implementations, the TOP pointer allows efficient dynamic memory management, both for pushing by pointing to the new head of the list and for popping by moving to the next node, thus maintaining stack integrity and preventing errors .

Array-based stacks offer simple memory management and faster access times due to contiguous memory allocation, but they have a fixed size, which can cause overflow if the maximum size is reached . Linked list stacks provide dynamic sizing, flexible memory use, and no risk of overflow specific to a fixed capacity, but they involve more complex memory management with additional overhead due to dynamic allocation and pointer manipulation .

Key operations on a stack include PUSH, POP, and PEEK. PUSH adds a new element to the top of the stack, updating the TOP pointer . POP removes the top element, decreasing the TOP pointer, with checks for underflow . PEEK allows viewing an element at a specific position from the top without modifying the stack .

In software systems, stack overflow usually mirrors scenarios where resources (e.g., memory, threads) might run out, as in recursive function calls without base cases, leading to uncontrolled resource consumption. Stack underflow reflects attempted read operations on empty data structures, which could result in unexpected behavior or crashes. Real-world error management echoes these concepts by using validation and handling mechanisms (e.g., garbage collection, exception handling) to gracefully manage such scenarios and ensure system stability .

In a linked list-based stack, the push operation involves dynamically allocating memory for a new node, inserting the new element at the top by adjusting pointers (NEW_NODE->NEXT=TOP and TOP=NEW_NODE). This differs from an array-based stack that requires checking for overflow, incrementing the TOP index, and placing the element in the array at TOP position. While a linked list allows for flexible growth by avoiding fixed-size limitations, the array method offers simpler memory management with fixed-size data structures .

In an array implementation of a stack, the memory is statically allocated, meaning that the size of the stack is fixed, and checking for overflow happens if the TOP pointer equals the maximum allowable index (MAX-1). In contrast, a stack implemented using a linked list dynamically allocates memory, allowing for a theoretically unlimited stack size as long as the system has free memory. In this approach, each element insertion (PUSH operation) requires memory allocation for a new node, and deletion (POP operation) involves freeing the node, improving flexibility but adding overhead due to dynamic memory operations .

The potential errors in stack operations are stack overflow and stack underflow. Stack overflow occurs when there is an attempt to push an element onto a full stack, which is handled by checking if the TOP pointer equals MAX-1 before performing a push . Stack underflow happens when attempting to pop an element from an empty stack, which can be prevented by checking if the TOP pointer is -1 before a pop operation . Both situations require error handling through condition checking prior to operation execution.

The push operation in an array-based stack involves the following steps: 1) Check if the TOP equals MAX-1, which indicates stack overflow, in which case the operation stops; 2) Increment the TOP pointer by one; 3) Insert the new element at the position indicated by the updated TOP pointer .

To perform a pop operation using a linked list stack: 1) Check if TOP is NULL to determine if the stack is empty (underflow situation); 2) Use a pointer (PTR) to temporarily store the address of the TOP node; 3) Update TOP to point to the next node; 4) Free the memory space occupied by the original TOP node .

Stacks are used in various real-world applications: 1) Infix to Postfix conversion in compilers, which utilizes stacks to manage operators and ensure correct order of operations . 2) Balancing symbols in expressions, where stacks ensure matching of parentheses, brackets, etc., by pushing opening symbols and popping them when a matching closing symbol is encountered . 3) Function call management in programming, where the call stack keeps track of active subroutines, allowing the program to return control to calling functions upon completion .

You might also like