You are on page 1of 73

STACK

It’s easy
Let’s Learn
than linked
Stack
list
Course Learning Outcomes

At the end of the lesson students are expected to be able to:

• Understand stack concept and its structure.

• Understand operations that can be done on stack.

• Understand and know how to implement stack using array


and linked list.
Introduction to Stack
• Stack is a collection of items which is organized in a
sequential manner.
• Example: stack of books or stack of plates.
• All additions and deletions are restricted at one end, called
top.
• LAST IN FIRST OUT (LIFO) data structure.
What Is Stack?

• Stack is an abstract data type

• Adding an entry on the top (push)

• Deleting an entry from the top (pop)

• A stack is open at one end (the top) only. You can push
entry onto the top, or pop the top entry out of the stack.
Last-in First-out (LIFO)
Stack implementation

• Stack is an abstract data structure

• Item can be Integer, Double, String, and also can be any


data type, such as Employee, Student…

• How to implement a general stack for all those types?

• We can implement stack using array or linked list.


Stack implementation Using Array
• Size of stack is fixed during declaration.

• Item can be pushed if there is some space available,


need to check if stack is full.

• Need a variable called, top to keep track the top of a


stack.

• Stack is empty when the value of Top is –1.


Stack implementation Using Linked List

• Size of stack is flexible. Item can be pushed and


popped dynamically.

• Need a pointer, called top to point to top of stack.


Stack implementation Using Array
Stack implementation Using Array

Stack Operations:
• createStack()
• push(item)
“Stack can be visualized as
• pop( ) array, BUT the operations can
be done on top stack only. “
• isEmpty( )
• isFull( )
• stackTop()
Push() and pop() operations
Stack implementation Using Array

3 things to be considered for stack with array

1. Stack Empty : when top is -1.

2. Push operations: To insert item into stack

2 statements must be used

top = top + 1;

stack[top] = newitem;
Stack implementation Using Array

3. Pop operations: To delete item from stack.

2 statements should be used

Item = stack[top]; or stackTop();

top = top – 1;

• Item = stack[top]; statement is needed if we want to


check the value to be popped.
Stack implementation Using Array
Example Code 1:
#include <iostream>
using namespace std;

#define MAX 5
int stack[MAX];
int top;
int item;

Continue..
Stack implementation Using Array
void createStack(){ 4
top = -1; 3
} 2
1
0
top = -1 stack

Continue..
Stack implementation Using Array
bool isEmpty(){
return (top == -1);
}

bool isFull(){
return (top == MAX - 1);
}

Continue..
Stack implementation Using Array
void push(){
if(isFull()){
cout <<"\n\tSorry,Cannot push item.Stack is now full!"<<endl;
}else{ Example initial top = -1 and stack is empty.
top = -1 + 1;
top = top + 1; top = 0;
stack[0] = 10;
cout<<"\n\tEnter Item:";
cin>>item;
4
stack[top]=item; 3
} } 2
1
top = 0 10 0
stack
Continue..
Stack implementation Using Array
Example initial top = 0 and stack is not empty.
void pop(){ top = 0 - 1;
top = - 1;
if(isEmpty()){
cout<<"\n\tSorry,Cannot pop item.Stack is now
4
empty!"<<endl;
3
}else{ 2
cout<<"\n\tPopped value :"<<stack[top]<<endl; 1
0
top = top - 1; top = -1 stack
}
}

Continue..
Stack implementation Using Array

void stackTop(){
if(isEmpty())
cout<<"\n\tSorry, cannot get item at the top, because stack is
empty!"<<endl;
else
cout<<"\n\tItem at top is:"<<stack[top]<<endl;
}

Continue..
Stack implementation Using Array

void display(){
if(isEmpty()){
cout <<"\n\tSorry,There Is No Item In Stack To Be
Displayed!"<<endl;
}else{
cout <<"\n\tDisplay Items In Stack"<<endl;
for(int i=top; i >=0; i--){
cout<<"\n\t\tItem:"<<stack[i]<<endl;
}
}
}
Continue..
Stack implementation Using Array

int main(){
createStack();
int selection;
menu:
cout<<"\nPlease Choose Your Selection\n";
cout<<"\n1\tPush\n";
cout<<"\n2\tPop\n";
cout<<"\n3\tDisplay\n";
cout<<"\n\tSelection is:";
cin>>selection;

Continue..
Stack implementation Using Array

switch(selection){
case 1: push();
display();
stackTop();
goto menu;
break;
case 2: pop();
display();
stackTop();
goto menu;
break;
Continue..
Stack implementation Using Array
case 3:
display();
stackTop();
break;
}
return 0;
}
Stack implementation Using Linked List
Stack implementation Using Linked List

• Stack implemented using linked list – number of


elements in stack is not restricted to certain size.

• Dynamic memory creation, memory will be assigned to


stack when a new node is pushed into stack, and
memory will be released when an element being popped
from the stack.
Stack implementation Using Linked List

• Stack using linked list implementation can be empty or


contains a series of nodes.
Stack implementation Using Linked List

• Each node in a stack must contain at least 2 attributes:

• i) data – to store information in the stack.

• ii) pointer next (store address of the next node in the


stack
Stack implementation Using Linked List

• Basic operations for a stack implemented using linked


list:

i. createStack() – initialize top

ii. push(char) – insert item onto stack

iii. pop() – delete item from stack


Stack implementation Using Linked List

iv. isEmpty() – check whether a stack is empty.

v. stackTop() – get item at top

• isFull() operation is not needed since elements


can be inserted into stack without limitation to
the stack size.
Stack implementation Using Linked List

• Push and pop operations can only be done at the top ~


similar to add and delete in front of the linked list.
Linked List Implementation of Stack:
push() and pop() operations
head

NULL
0110
temp1
0110 Siti 25 next

name age next


temp1->next = head;
head = temp1;
head 0110

Push 0110 Siti 25 NULL

name age next


temp2

0111 Amy 35 next

name age next


temp2->next = head;
head = temp1;
Linked List Implementation of Stack:
push() and pop() operations
0111
head
Push 0111 Amy 35 0110

name age next

0110

Siti 25 NULL

name age next

temp3 0112

0112 Ayu 23 next

name age next


temp3->next = head;
head = temp3;
Linked List Implementation of Stack:
push() and pop() operations

head 0112
Push 0112 Ayu 23 0111
name age next

0111

Amy 35 0110

name age next

0110

Siti 25 NULL

name age next


Linked List Implementation of Stack:
push() and pop() operations
head 0112

Pop 0111 Ayu 23 0111


name age next

delnode 0111

0112 Amy 35 0110

name age next

0110

Siti 25 NULL

name age next

STEP 1 : delnode = head;


STEP 2 : head = delnode -> next; or head = head->next;
STEP 3 : delete(delnode);
Linked List Implementation of Stack:
push() and pop() operations
0111
head
After Pop 0111 Amy 35 0110

name age next

0110

Siti 25 NULL

name age next


Linked List Implementation of Stack:
push() and pop() operations
0111
head
Pop 0110 Amy 35 0110

name age next

delnode
0110
0111
Siti 25 NULL

name age next

STEP 1 : delnode = head;


STEP 2 : head = delnode -> next; or head = head->next;
STEP 3 : delete(delnode);
Linked List Implementation of Stack:
push() and pop() operations

head 0110
After Pop 0110 Siti 25 NULL

name age next


push() operations

• 2 conditions for inserting element in stack:

– Insert to empty stack.

– Insert item to non empty stack : stack with value.


push() to empty stack
head
NULL

temp 0123
0123 Ana 25 next
name age next

In this situation the new node being inserted,


will become the first item in stack.
STEP 1 : temp->next = head;
STEP 2 : head = temp;
push() to empty stack

head 0123
0123 Ana 25 NULL
name age next
push() to non-empty stack

• This operation is similar to inserting element in front of a


linked list. The next value for the new element will point
to the top of stack and head will point to the new
element.
push() to non-empty stack

head 0110 0111


0110 Ali 20 0111 Abu 30 NULL
name age next name age next

temp STEP 1 : temp->next = head


0112 Ahmad 35 next
name age next
STEP 2 : head = temp

STEP 1 : temp->next = head;


STEP 2 : head = temp;
push()to non-empty stack

head 0112 0110


0112 Ahmad 35 0110 Ali 20 0111
name age next name age next

0111
Abu 30 NULL
name age next
pop() to non-empty stack

• Pop operation can only be done to non-empty stack. Before pop()


operation can be done, operation must be called in order to check
whether the stack is empty or there is item in the stack. If isEmpty()
function return true, pop() operation cannot be done.
• During pop() operation, an external pointer is needed to point to the
delete node. In the figure below, delnode is the pointer variable to
point to the node that is going to be deleted.
pop() to non-empty stack
STEP 1 : delnode = head;

head 0112 0110


0112 Ahmad 35 0110 Ali 20 0111
name age next name age next
delnode
0112 0111
Abu 30 NULL
name age next
pop() to non-empty stack

STEP 2 : head = delnode -> next;


head 0112 0110

0110 Ahmad 35 0110 Ali 20 0111


name age delnode->next name age next

delnode

0112 0111

Abu 30 NULL
name age next
pop() to non-empty stack

STEP 3 : delete delnode;

head 0112 0110

0110 Ahmad 35 0110 Ali 20 0111


name age delnode->next name age next
delnode

0112
0111

Abu 30 NULL
name age next
Stack implementation Using Linked List
#include<iostream>
using namespace std;
struct person{
char name[20];
int age;
person *link;
};
person *strt = NULL;

Continue..
Stack implementation Using Linked List
void push(){
//create new node
person *node1;
node1=new person;
//enter data
cout<<"\n\tEnter Name:";
cin>>node1->name;
cout<<"\n\tEnter Age:";
cin>>node1->age;
node1->link=strt;
strt=node1;
}

Continue..
Stack implementation Using Linked List
void pop(){
//check stack is empty
if(strt == NULL){
cout<<"\n\tStack Is Empty, Cannot Delete Node\n";
}else{
person *delnode;
delnode=strt;
strt=delnode->link;
delete delnode;
cout<<"\n\tNode Is Successfully Deleted\n";
}
}

Continue..
Stack implementation Using Linked List
void stackTop(){
if(strt == NULL){
cout<<"\n\tStack Is Empty, There Is No Node At Top Of Stack\n";
}else{
cout<<"\n\tData In Node At Top Of Stack\n";
cout<<"\n\t\tName:"<<strt->name<<endl;
cout<<"\n\t\tAge:"<<strt->age<<endl;
}
}

Continue..
Stack implementation Using Linked List
void display(){
person *cursor;
int i=1;
cout<<"\n\tDisplay Data In Stack\n";
for(cursor=strt; cursor != NULL; cursor=cursor->link){
cout<<"\n\t\tNode:"<<i<<endl;
cout<<"\n\t\tName:"<<cursor->name<<endl;
cout<<"\n\t\tAge:"<<cursor->age<<endl;
i++;
}
}

Continue..
Stack implementation Using Linked List
int main()
{
int selection;
menu:
cout<<"\nPlease Choose Your Selection\n";
cout<<"\n1\tPush\n";
cout<<"\n2\tPop\n";
cout<<"\n3\tDisplay\n";
cout<<"\n\tSelection is:";
cin>>selection;

Continue..
Stack implementation Using Linked List
switch(selection){
case 1: push();
display();
stackTop();
goto menu;
break;
case 2: pop();
display();
stackTop();
goto menu;
break;

Continue..
Stack implementation Using Linked List
case 3:display();
stackTop();
break;
}
return 0;
}
Stack Application Examples

• Check whether parantheses are balanced (open and closed


parantheses are properly paired)

• Evaluate Algebraic expressions.

• Creating simple Calculator

• Backtracking (example. Find the way out when lost in a


place)
Example 1 : Parantheses Balance

• Stack can be used to recognize a balanced parentheses.


• Examples of balanced parentheses.
(a+b), (a/b+c), a/((b-c)*d)
Open and closed parentheses are properly paired.
• Examples of not balance parentheses.
((a+b)*2 and m*(n+(k/2)))
Open and closed parentheses are not properly paired.
Check for Balanced Parantheses Algorithm

• Every ‘(’ read from a string will be pushed into stack.

• The open parentheses ‘(’ will be popped from a stack


whenever the closed parentheses ‘)’ is read from string.
Check for Balanced Parantheses Algorithm

• An expression have balanced parentheses if :

– Each time a “)” is encountered it matches a previously


encountered “(“.

– When reaching the end of the string, every “(“ is


matched and stack is finally empty.
Check for Balanced Parantheses Algorithm

• An expression does NOT have balanced parentheses if :

– When there is still ‘)’ in input string, the stack is


already empty.

– When end of string is reached, there is still ‘(‘ in stack.


Example for Balance Parantheses

Every ( is Insert into stack Pop ( when found )


3 3 3 3
2 2 2 2
1 1 ( 1 1
0 ( 0 ( 0 ( 0

Push(() Push(() Pop() Pop()


Expression a(b(c)) have balance parentheses since when end of
string is found the stack is empty.
Example for Unbalanced Parentheses

Every ( is Insert into stack Pop ( when found )


3 3 3 3 3
2 2 2 2 2
1 1 ( 1 1 1
0 ( 0 ( 0 ( 0 0

Push(() Push(() Pop() Pop() Pop()->fail


Expression a(b(c))) f does not have balance parentheses => the
third ) encountered does not has its match, the stack is empty.
Algebraic expression

• One of the compiler’s task is to evaluate algebraic


expression.

• Example of assignment statement:

y=x+z*(w/x+z*(7+6))
Algebraic expression

• Compiler must determine whether the right expression is


a syntactically legal algebraic expression before
evaluation can be done on the expression.

• 3 algebraic expressions are :

Infix, prefix and postfix


Infix Expression

• The algebraic expression commonly used is infix.

• The term infix indicates that every binary operators


appears between its operands.

• Example 1:

• Example 2: A+B*C
Infix Expression

• To evaluate infix expression, the following rules were


applied:

1. Precedence rules(peraturan keutamaan).

2. Association rules (associate from left to right)

3. Parentheses rules (peraturan kurungan)


Prefix and Postfix Expressions

• Alternatives to infix expression


• Prefix : Operator appears before its operand.
• Example:
Prefix and Postfix Expressions

• Postfix : Operator appears after its operand.


• Example:
Infix, prefix and postfix

The advantage of using prefix and postfix is that we don’t need


to use precedence rules, associative rules and parentheses
when evaluating an expression.
Converting Infix to Prefix
Steps to convert infix expression to prefix:
STEP 1 : Determine the precedence.

STEP 2 :
Converting Infix to Postfix
Exercise 1

• Convert infix to prefix


i. a+b
ii. a + b * c
iii. a + b * (c-d) / (p-r)
Exercise 2

• Convert infix to postfix


i. a+b
ii. a + b * c
iii. a + b * (c-d) / (p-r)

You might also like