To implement the Stack data structure in C++ using two different approaches and demonstrate stack operations such as push, pop, display, and top element retrieval.
A stack is a linear data structure that follows the LIFO (Last In, First Out) principle.
- Push: Insert an element into the stack.
- Pop: Remove the top element of the stack.
- Peek/Top: Access the top element without removing it.
- isEmpty: Check whether the stack is empty.
- isFull: Check whether the stack is full (only in array-based implementation).
Stacks are widely used in expression evaluation, function calls (recursion), and undo mechanisms.
- Start.
- Create a
Stack
class with attributes:maxSize
,topIndex
, and a dynamically allocated arraydata
. - Initialize
topIndex = -1
. - Push operation:
- If
topIndex < maxSize - 1
, incrementtopIndex
and insert the value atdata[topIndex]
. - Else, print "Stack Overflow".
- If
- Pop operation:
- If
topIndex >= 0
, decrementtopIndex
. - Else, print "Stack Underflow".
- If
- Top element retrieval:
- If stack is not empty, return
data[topIndex]
. - Else, return
-1
.
- If stack is not empty, return
- Perform operations in
main()
and display results. - Stop.
- Start.
- Create a
Stack
class with attributes:arr[MAX]
andtop
. - Initialize
top = -1
. - isFull(): Returns true if
top == MAX - 1
. - isEmpty(): Returns true if
top == -1
. - Push operation:
- If
isFull()
, print "Stack Overflow". - Else, increment
top
and insert the value atarr[top]
.
- If
- Pop operation:
- If
isEmpty()
, print "Stack Underflow". - Else, print and decrement
arr[top]
.
- If
- Display operation:
- If stack is empty, print "Stack is empty".
- Else, display elements from
arr[top]
toarr[0]
.
- In
main()
, create a menu-driven program with options for Push, Pop, Display, and Exit. - Perform operations until the user exits.
- Stop.
The stack data structure was successfully implemented in C++ using both dynamic memory allocation and static array with menu-driven operations.
Both implementations demonstrate fundamental stack operations and verify the LIFO principle.