You are on page 1of 20

Benha University

Electrical Engineering Department Benha Faculty of Engineering


Today’s discussion…

*Stack
*Basic principles
*Operation of stack
*Implementation Stack using Array
*Applications of stack
What is a stack?

 A stack is also an ordered collection of elements like arrays, but it has a


special feature that deletion and insertion of elements can be done only from
one end called the top of the stack (TOP)
 Due to this property, it is also called as last in first out type of data structure
(LIFO).
Stack operations:
push(v): adds a value v at the top of the stack
pop(): removes and returns value at top
isEmpty(): returns true or false
isFull(): returns true or false
top(): returns copy of value at top of stack (without removing it)

push

pop STACK
isEmpty

4
isFull
Push (ItemType newItem) Pop (ItemType& item)
 Function: Adds newItem to  Function: Removes topItem from
the top of the stack. stack.
 Preconditions: Stack has  Preconditions: Stack has been
been initialized and is not initialized and is not empty.
full.  Postconditions: Top element has
 Postconditions: newItem is at been removed from stack.
the top of the stack.
Stack overflow
 The condition resulting from trying to push an element onto a full stack.
if(!stack.IsFull())
stack.Push(item);

Overflow occurs when top = Maxsize -1

Stack underflow
 The condition resulting from trying to pop an empty stack.
if(!stack.IsEmpty())
stack.Pop(item);
Common Uses for Stacks
Stacks are one of the most USEFUL data structures in Computer Science.

So how does the UNDO feature of Undo! your favorite


word processor work?
• It uses a stack, of course! Every time you type a
new word, it’s added to the stack!. Every time you
cut-and-paste an image into your doc, it’s added to
the stack! And even when you delete text or
pictures, this is tracked on a stack!

When the user hits the undo button…


The word processor pops the top item off the stack
“so” the word processor can track the last X things
that you did and properly undo them!
• Web browsers history store the addresses of recently visited sites
on a stack • Each time the visits a new site ==> pushed on the
stack. Browsers allow to “pop” by back button to previously visited
site.
• Check that all brackets match.
• Converting from infix expressions to postfix expressions
A+B→AB+

• Evaluating mathematical expressions(Postfix and prefix)


5 + 6 * 3 → 23

• Decimal to binary convert.


8
Stacks Array Based Implementation
#include<iostream> bool empty() void show()
#include<string> { {
#define size 10 if (top==-1) if (top==-1)
using namespace std; return true; {
class stack else cout<<"stack is empty\n";
{ return false; }
private: } else
int top; {
int data[size]; bool full() for (int i=top; i>=0; i--)
public: { {
if (top==size-1) cout<< data[i]<< endl;
stack() return true; }
{ else }
top=-1; return false }
} } };

9
void push(int n) void pop()
{
if (full()) {
{ if(empty())
cout<< "stack is full\n"; {
} cout<<"stack is empty\n";
else }
{ else
data[++top]=n; {
} cout<< data [top--];
}
}
}

Push:
•Increment the variable top so that Pop:
it can refer to the next memory •Decrement the value of the top
allocation •Return the topmost element
•Copy the item to the array index
value equal to the top
•Repeat step 1 and 2 until stack
overflows
1- Balanced brackets check Application
Check that all brackets match:
●Every opening bracket has a closing bracket
●Every closing bracket has an opening bracket
●Nested brackets match up: no!”])[(“
bool balanced(string exp)
{
stack open_brakets; bool pair(char open,char close)
for (int i=0; i< exp.length();i++) {
{
if (exp[i]=='(' ||exp[i]=='{'||exp[i]=='[') if (open=='(' && close==')') return true;
open_brakets.push(exp[i]); else if (open=='{' && close=='}') return true;
else if (open=='[' && close==']') return true;
else if(exp[i]==')' ||exp[i]=='}'||exp[i]==']') else return false;
{ }
if (open_brakets.empty())
return false;
int top_val()
else if (pair(open_brakets.top_val(), exp[i])== false)
return false; {
if (empty()) return -1;
open_brakets.pop(); return data[top];
}
} }
if (open_brakets.empty()) return true;
else return false;
}
2- Infix to postfix Conversion
Since people are more used to
Stacks can also be used to convert infix expressions infix notation…
to postfix expressions:
You can let the user type in an
Postfix notation is another way of infix expression…

writing arithmetic expressions. And then convert it into a


postfix expression.

Finally, you can use the postfix


 In postfix notation, the operator evaluation alg (that we just
learned)
is written after the two operands. to compute the value of the
expression.

infix: 2+5 postfix: 2 5 +


 Expressions are evaluated from left to right.
Postfix notation Priority
is also called as Brackets
Reverse Polish */%
Notation (RPN) +-
2- Infix to postfix Conversion
By Algorithm

EX : (3+2)+7/2 * ((7+3)*2)

stack

OUTPUT: 32+72/73+2**+
string infix_to_postfix(string exp)
int priority(char c)
{ while(!stk.empty()&& priority(exp[i])
{
stack stk; <= priority(stk.top()))
if (c=='-' || c=='+')
string output=""; {
return 1;
for(int i=0; i<exp.length();i++) output +=stk.top();
else if (c=='*' || c=='/')
{ stk.pop();
return 2;
if(exp[i]==' ') continue; }
else if (c=='^')
if (isdigit (exp[i])||isalpha(exp[i])) stk.push(exp[i]);
return 3;
output += exp[i]; }
else
else if(exp[i]=='(') }
return 0;
stk.push('(');
}
else if (exp[i] ==')')
{ while(!stk.empty())
int main() while(stk.top()!= '(') {
{ { output +=stk.top();
string infixexpression= output +=stk.top(); stk.pop();
("(3+2)+7/2*((7+3)*2)"); stk.pop(); }
cout<< infix_to_postfix } return output;
(infixexpression)<<endl; stk.pop();// remove '(' }
return 0; }
} else
{
Postfix Evaluation Algorithm
Inputs: postfix expression string
Output: number representing answer

1. Start with the left-most token.


2. If the token is a number: Push it onto the stack

3. Else if the token is an operator:


a. Pop the top value (second operand v2), and the first
operand value v1.
b. Apply operator to v1 and v2 (e.g., v1 / v2)
c. Push the result of the operation on the stack

4. If there are more tokens, advance to the next token and go


back to step #2

5. After all tokens have been processed, the top # on the


stack is the answer!
float mathoperation(float op1,float op2,char operat)
float postfix_evaluate(string exp)
{
{
if (operat =='+')
return op1+op2; stack<float> stk;
else if (operat =='-') for (int i=0; i<exp.length(); i++)
return op1-op2; {
else if (operat =='*') if (isdigit(exp[i]))
return op1*op2; stk.push(exp[i]-'0');
else if (operat =='/') else{
return op1/op2; float op2= stk.top();
else return 0; stk.pop();
} float op1= stk.top();
stk.pop();
float result=mathoperation(op1,op2,exp[i]);
int main()
stk.push(result);
{
}
string postfixexpression="382/+5-";
}
cout<< postfix_evaluate(postfixexpression)<<endl;
return stk.top(); // final answer from stack
return 0;
}
}

Char ‘0’ = ascii 48


Char ‘3’= ascii 51

You might also like