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

Array and List Implementation: Stack

Stacks are a data structure that follow the LIFO (last in, first out) principle. Elements are inserted and removed from only one end, called the top. Common stack operations include push to insert an element, pop to remove an element, and peek/top to view the top element. Stacks have numerous applications like undo functions, function call stacks, parsing expressions, and more. They can be implemented using either arrays or linked lists.

Uploaded by

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

Array and List Implementation: Stack

Stacks are a data structure that follow the LIFO (last in, first out) principle. Elements are inserted and removed from only one end, called the top. Common stack operations include push to insert an element, pop to remove an element, and peek/top to view the top element. Stacks have numerous applications like undo functions, function call stacks, parsing expressions, and more. They can be implemented using either arrays or linked lists.

Uploaded by

Umer Salam
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Stack

Array and list implementation


Stacks
“A Stack is a special kind of list that has only
one open end

Other Names
 Pushdown List
 Last In First Out (LIFO)

2
What is a Stack?
• A stack is a structure with the restriction that
insertions and deletions can be performed in only
one position, namely, the end of the list, called the
top.
• The operations: push (insert) and pop (delete)
pop push(o)

Top 3
2
7
6
12/18/2021 CS 201
Stacks
Examples:

 Books on a floor

 Dishes on a shelf

4
Static and Dynamic Stacks
• There are two kinds of stack data structure -

– a) static, i.e. they have a fixed size, and are


implemented as arrays.

– b) dynamic, i.e. they grow in size as needed, and


implemented as linked lists

5
Common Operations on Stacks
1. MAKENULL(S): Make Stack S be an empty stack.
2. TOP(S): Return the element at the top of stack S.
3. POP(S): Remove the top element of the stack.
4. PUSH(S): Insert the element x at the top of the
stack.
5. EMPTY(S): Return true if S is an empty stack; return
false otherwise.

6
Stack ADT Interface

• The main functions in the Stack ADT are (S is the stack)

boolean isEmpty(); // return true if empty

boolean isFull(S); // return true if full

void push(x); // insert item into stack

void pop(); // remove most recent item

int top(); // retrieve most recent item

12/18/2021 CS 201
Sample Operation
Stack S = malloc(sizeof(stack));

push(S, “a”);

push(S, “b”); s

push(S, “c”); d
top
d=top(S);

e
pop(S);

c
push(S, “e”);

b
pop(S);

a
12/18/2021 CS 201
Implementation by Array
 Elements are stored in contiguous cells of an array.
 New elements can be inserted to the top of the list.
StackAr

arr

0 1 3 4 6 7 8 9
2 5

A A B C D E F

top

12/18/2021 CS 201
Array-based Stack
• A simple way of Algorithm size()
return t + 1
implementing the
Stack ADT uses an Algorithm empty()
array return size () == 0
• We add elements
Algorithm pop()
from left to right if empty() then
• A variable keeps track throw EmptyStackException
of the index of the else
tt1
top element return S[t + 1]


S
0 1 2 t
Array-based Stack (cont.)
• The array storing
the stack elements Algorithm push(e)
if t = S.length  1 then
may become full throw FullStackException
else
• A push operation tt+1
S[t]  e
will then give an
ERROR


S
0 1 2 t
A Stack Class
class IntStack
{
private:
int *stackArray;
int stackSize;
int top;
public:
IntStack(int); // Constructor
void push(int);
void pop(int &);
bool isFull(void);
bool isEmpty(void);
};

12
Implementation
//*******************
// Constructor *
//*******************
IntStack::IntStack(int size)
{
stackArray = new int[size];
stackSize = size;
top = -1;
}

13
Push
// Member function push pushes the argument onto
// the stack.
void IntStack::push(int num)
{
if (isFull())
cout << "The stack is full.\n";
else
{
top++;
stackArray[top] = num;
}
}
14
// Member function pop pops the value at the top
// of the stack off, and copies it into the variable
// passed as an argument.
void IntStack::pop(int &num)
{
if (isEmpty())
cout << "The stack is empty.\n";
else
{
num = stackArray[top];
top--;
}
}

15
//***************************************************
// Member function isFull returns true if the stack *
// is full, or false otherwise. *
//***************************************************

bool IntStack::isFull(void)
{
bool status;

if (top == stackSize - 1)
status = true;
else
status = false;

return status;
}

16
//**********************************************
// Member funciton isEmpty returns true if the
//stack *
// is empty, or false otherwise.*
//***********************************************
bool IntStack::isEmpty(void)
{
bool status;

if (top == -1)
status = true;
else
status = false;

return status;
}

17
// This program demonstrates the IntStack class.
#include <iostream.h>
#include "intstack.h“

void main(void)
{
IntStack stack(5);
int catchVar;

cout << "Pushing 5\n";


stack.push(5);
cout << "Pushing 10\n";
stack.push(10);
cout << "Pushing 15\n";
stack.push(15);
cout << "Pushing 20\n";
stack.push(20);
cout << "Pushing 25\n";
stack.push(25);
18
cout << "Popping...\n";
stack.pop(catchVar);
cout << catchVar << endl;
stack.pop(catchVar);
cout << catchVar << endl;
stack.pop(catchVar);
cout << catchVar << endl;
stack.pop(catchVar);
cout << catchVar << endl;
stack.pop(catchVar);
cout << catchVar << endl;
}

19
Program Output
Pushing 5
Pushing 10
Pushing 15
Pushing 20
Pushing 25
Popping...
25
20
15
10
5

20
Performance and Limitations
(array-based implementation of stack ADT)

• Performance
– Let n be the number of elements in the stack
– The space used is O(n)
– Each operation runs in time O(1)
• Limitations
– The maximum size of the stack must be defined a
priori , and cannot be changed
– Trying to push a new element into a full stack causes
an error
Dynamic Stack Features

• No stack overflow
– No limit of inserting new node into the stack
until main memory allows
• Consumes less memory space
• No continuous memory space required like
array
• Pointers are used to store address of next
element
Dynamic allocation of each
stack element

• Allocate memory for


each new element
dynamically

itemPtr = new ItemType;


*itemPtr = newItem;
Dynamic allocation of each
stack element (cont.)

• How should we preserve the order of the


stack elements?
Chaining the stack elements
together
Chaining the stack elements together (cont.)

• Each node in the stack should contain two


parts:
– info: the user's data
– next: the address of the next element in the
stack
Implementation by Linked Lists
• Can use a Linked List as implementation of stack

StackLL

lst Top of Stack = head of Linked-List


LinkedListItr

head

a1 a2 a3 a4

12/18/2021
Dynamic Stack- C++ Code

12/18/2021
12/18/2021
Applications of Stacks
• Page-visited history in a Web browser
• Undo sequence in a text editor
• Saving local variables when one function calls
another, and this one calls another, and so on.
• line editing
• bracket matching
• postfix calculation
Line Editing
• A line editor would place characters read into a
buffer but may use a backspace symbol (denoted by
) to do error correction
• Refined Task
– read in a line
– correct the errors via backspace
– print the corrected line in reverse

Input : abc_defgh2klpqrwxyz
Corrected Input : abc_defg2klpwxyz
Reversed Output : zyxwplk2gfed_cba

12/18/2021
The Procedure
• Initialize a new stack
• For each character read:
– if it is a backspace, pop out last char
entered
– if not a backspace, push the char into
stack
• To print in reverse, pop out each char for
output
r
z
h
Input : fghryz g
y
Corrected Input : fyz f

Reversed Output : zyf Stack

12/18/2021

You might also like