Stacks
Prof. Dr. Hanafy Ismail 1
What is a stack? • • •
It is an ordered group of homogeneous items (all of the same type) of elements. Elements are added to and removed from the top of the stack (the most recently added items are at the top of the stack). The last element to be added is the first to be removed (LIFO: Last In, First Out structure).
Prof. Dr. Hanafy Ismail 2
What is a stack? TOP
Last element ……..
First Element
BOTTOM
STACK Prof. Dr. Hanafy Ismail 3
What is a stack?
• The first element represents the BOTTOM of •
the stack. The last element represents the top of the stack. The stack contains a pointer (TOP) which points to the top of the stack. The stack represents a collection of consecutive memory locations; these locations are accessed from the top of the stack Prof. Dr. Hanafy Ismail 4
What is a stack?
• When the stack is empty
TOP = BOTTOM = -1
• When an item is added to the stack, it is pushed onto the stack
TOP = TOP + 1
• When an item is removed, it is popped from the stack
TOP = TOP -1 Prof. Dr. Hanafy Ismail 5
Methods of Stack Implementation
1. Implementation of stack as an Array 2. Implementation of stack as a list (using pointers).
Prof. Dr. Hanafy Ismail 6
Representing Stack in C • •
Implementation of stack as an array based structure A stack can be declared as a structure of two objects:
•
# define MAX_ITEMS 100 struct stack {
– An array to hold the elements of the stack – an integer to indicate the position of the current stack top within array.
int top; stackelement
items [ MAX_ITEMS ];
} The definition of the stackelement is determined by the user of the stack ( char , int, char *, .. etc)
Prof. Dr. Hanafy Ismail 7
Operations on the stack • •
•
Given a stack S declared by: struct stack S; ISEMPTY ( test whether or not a stack is empty) int isempty ( struct stack * ps) { return ( ps top == -1 ); / * returns true if the stack is empty }
ISFULL ( test whether or not a stack is full) int isfull ( struct stack * ps) { return ( ps top == MAX_ITEMS -1 ); / * returns true if the stack is full }
Prof. Dr. Hanafy Ismail 8
Operations on the stack •
POP operation ( delete an element from the stack) int pop ( struct stack *ps ) { if ( isempty (ps) ) { cout << "stack underflow"; exit(1); } return ( ps -> items [ps -> top--] ); /* remove the top element from the stack and return }
Prof. Dr. Hanafy Ismail 9
Operations on the stack â&#x20AC;˘
PUSH operation ( add a new element to the stack) void push (struct stack *ps, int x) { if ( ps -> top == MAX_ITEMS - 1) { cout << "stack overflow"; exit(1); } else ps -> items [ ++( ps -> top ) ] = x ; return; }
Prof. Dr. Hanafy Ismail 10
Operations on the stack â&#x20AC;˘
STACKTOP operation ( retrieve the top element of the stack without removing it from the stack ) int stacktop ( struct stack *ps ) { if (empty (ps) ) { cout << "stack underflow"; exit(1); } return ( ps -> items [ ps -> top ] ); }
Prof. Dr. Hanafy Ismail 11
Operations on the stack
• MakeEmpty (clear the stack; remove all elements)
void MakeEmpty ( struct stack * ps) { ps top = -1 ; }
Prof. Dr. Hanafy Ismail 12
Stack Specification in C++ • Definitions: (provided by the user)
– MAX_ITEMS: Max number of items that might be on the stack – ItemType: Data type of the items on the stack – The elements of a stack can be simple (for example integers or characters) or structured (for example stack of structures)
• Operations – – – – –
MakeEmpty Boolean IsEmpty Boolean IsFull Push (ItemType newItem) Pop (ItemType& item) Prof. Dr. Hanafy Ismail 13
Push (ItemType newItem)
• Function: Adds newItem to the top of the stack. • Preconditions: Stack has been initialized and is not full. • Postconditions: newItem is at the top of the stack. Prof. Dr. Hanafy Ismail 14
Pop (ItemType& item)
• Function: Removes topItem from stack and • •
returns it in item. Preconditions: Stack has been initialized and is not empty. Postconditions: Top element has been removed from stack and item is a copy of the removed element. Prof. Dr. Hanafy Ismail 15
Prof. Dr. Hanafy Ismail 16
Stack Implementation in C++ (as an array) #include "ItemType.h" // Must be provided by the user of the class // Contains definitions for MAX_ITEMS and ItemType class StackType { public: StackType(); void MakeEmpty(); bool IsEmpty() const; bool IsFull() const; void Push(ItemType); void Pop(ItemType&); private: int top; ItemType items[MAX_ITEMS]; };
Prof. Dr. Hanafy Ismail 17
Stack Implementation (cont.) StackType::StackType() { top = -1; } void StackType::MakeEmpty() { top = -1; } bool StackType::IsEmpty() const { return (top == -1); } Prof. Dr. Hanafy Ismail 18
Stack Implementation (cont.) bool StackType::IsFull() const { } {
} {
}
return (top == MAX_ITEMS-1); void StackType::Push(ItemType newItem) top++; items[top] = newItem; void StackType::Pop(ItemType& item) item = items[top]; top--; Prof. Dr. Hanafy Ismail 19
Stack overflow
â&#x20AC;˘ The condition resulting from trying to push an element onto a full stack. if(!stack.IsFull()) stack.Push(item);
Stack underflow
â&#x20AC;˘ The condition resulting from trying to pop an empty stack.
if(!stack.IsEmpty()) stack.Pop(item); Prof. Dr. Hanafy Ismail 20
Implementing stacks using templates
â&#x20AC;˘ Templates allow the compiler to generate â&#x20AC;˘
multiple versions of a class type or a function by allowing parameterized types. It is similar to passing a parameter to a function (we pass a data type to a class !!)
Prof. Dr. Hanafy Ismail 21
Implementing stacks using templates template<class ItemType> (cont.) class StackType { public: StackType(); void MakeEmpty(); bool IsEmpty() const; bool IsFull() const; void Push(ItemType); void Pop(ItemType&); private: int top; ItemType items[MAX_ITEMS]; }; Prof. Dr. Hanafy Ismail 22
Example using templates // Client code StackType<int> myStack; StackType<float> yourStack; StackType<StrType> anotherStack; myStack.Push(35); yourStack.Push(584.39);
The compiler generates distinct class types and gives its own internal name to each of the types. Prof. Dr. Hanafy Ismail 23
Function templates â&#x20AC;˘ The definitions of the member functions must be rewritten as function templates.
template<class ItemType> StackType<ItemType>::StackType() { top = -1; } template<class ItemType> void StackType<ItemType>::MakeEmpty() { top = -1; } Prof. Dr. Hanafy Ismail 24
Function templates (cont.) template<class ItemType> bool StackType<ItemType>::IsEmpty() const {
return (top == -1); }
template<class ItemType> bool StackType<ItemType>::IsFull() const {
return (top == MAX_ITEMS-1); }
template<class ItemType> void StackType<ItemType>::Push(ItemType newItem) {
top++; items[top] = newItem; } Prof. Dr. Hanafy Ismail 25
Function templates (cont.) template<class ItemType> void StackType<ItemType>::Pop(ItemType& item) { item = items[top]; top--; }
Prof. Dr. Hanafy Ismail 26
Comments using templates
â&#x20AC;˘ The template<class T> designation must â&#x20AC;˘ â&#x20AC;˘
precede the class method name in the source code for each template class method. The word class is required by the syntax of the language and does not mean that the actual parameter must be the name of a class. Passing a parameter to a template has an effect at compile time. Prof. Dr. Hanafy Ismail 27
Implementing stacks using dynamic array allocation in C++ template<class ItemType> class StackType { public: StackType(int); ~StackType(); void MakeEmpty(); bool IsEmpty() const; bool IsFull() const; void Push(ItemType); void Pop(ItemType&);
private: int top; int maxStack; ItemType *items; };
Prof. Dr. Hanafy Ismail 28
Implementing stacks using dynamic array allocation (cont.) template<class ItemType> StackType<ItemType>::StackType(int max) {
maxStack = max; top = -1; items = new ItemType[max]; }
template<class ItemType> StackType<ItemType>::~StackType() {
delete [ ] items; } Prof. Dr. Hanafy Ismail 29
Use a stack to reverse the order of characters in the a string •
•
void input_stack (struct stack *sp) { char c; cout << “ Enter a string of characters”; while ( c = getchar () != ‘\n’) && (! isfull(stack)) push (sp , c); } void output_stack (struct stack *sp) { char c; cout << “ string reversed ---- ”; while ( ! isempty ( sp)) { c = pop (sp ); cout << c; } }
Prof. Dr. Hanafy Ismail 30
Example: postfix Arithmetic using stack
• Postfix notation is another way of writing arithmetic expressions.
• In postfix notation, the operator is written after the two operands.
•
infix: 2+5 postfix: 2 5 + Expressions are evaluated from left to right.
• Precedence rules and parentheses are never needed!! Prof. Dr. Hanafy Ismail 31
Example: postfix expressions (cont.)
Prof. Dr. Hanafy Ismail 32
Converting infix expressions to postfix expressions
1. 2. 3. 4.
Enclose all arithmetic operations according to its implementation priorities with parentheses The number of right parentheses must equal to the number of left parentheses and equal to the number of arithmetic operations. Eliminate all left parentheses from the mathematical expression. Replace each right parentheses with the associated operator. Prof. Dr. Hanafy Ismail 33
Converting infix expressions to postfix expressions: Examples
â&#x20AC;˘
1. 2. 3. 4.
Example1: convert the expression B + C * 2 from infix to postfix.
(B+(C*2)) no. of R. Par. = no. of L. Par. = no. of operations = 2 B + C * 2 ) ) B C 2 * + Prof. Dr. Hanafy Ismail 34
Converting infix expressions to postfix expressions: Examples
â&#x20AC;˘ 1. 2. 3. 4.
Example2: convert the expression B/C*(A+B) from infix to postfix. ((B/C)*(A+B)) no. of R. Par. = no. of L. Par. = no. of operations = 3 B/C )*A+B ) ) B C / A B+ * Prof. Dr. Hanafy Ismail 35
Converting infix expressions to postfix expressions: Examples
• 1. 2. 3. 4.
Example3: convert the expression (C+2)/ (A+B-C)*3 from infix to postfix. (((C+2)/((A+B)-C))*3) no. of R. Par. = no. of L. Par. = no. of operations = 5 C+2) /A+B )–C ))*3) C 2+ A B+ C -/ 3* Prof. Dr. Hanafy Ismail 36
Converting an expression from infix to postfix using stack: Algorithm
• •
•
Add operands (variables and constants) to postfix string as they are read in the input infix expression When an operator is input – While ( the stack is not empty and operator precedence >= precedence of the operator in the top of the stack ) • Pop the operator in the top of the stack and add it to the postfix string; – If the stack is empty or the operator is not ‘)’ • Then push the operator onto the stack – Else • Pop the open parentheses and discard it When the end-of-line character is input – output any remaining operators in the stack and add them to the postfix string
Prof. Dr. Hanafy Ismail 37
Converting an expression from infix to postfix using stack: Example â&#x20AC;˘
Using stack convert infix : (A + B ) * C to postfix: AB+C * symbol
Postfix string
(
stack (
A
A
(
+
A
(+
B
AB
(+
)
AB+
*
AB+
*
C
AB+C
*
AB+C*
Prof. Dr. Hanafy Ismail 38
Postfix expressions: Algorithm using stacks (cont.)
Prof. Dr. Hanafy Ismail 39
Postfix expressions: Algorithm using stacks WHILE more input items exist Get an item IF item is an operand stack.Push(item) ELSE stack.Pop(operand2) stack.Pop(operand1) Compute result stack.Push(result) stack.Pop(result) Prof. Dr. Hanafy Ismail 40
Program to evaluate postfix expression using stack • • • • • • • • • • •
#include<stdio.h> #include<iostream.h> #include<stdlib.h> #include<conio.h> #define max 100 double pop(struct stack *); void push(struct stack *,double); int empty(struct *); int isdigit(char); double eval(char[]); double oper(int,double,double); Prof. Dr. Hanafy Ismail 41
Program to evaluate postfix expression using stack • • • • • • • • • •
void main() { char expr[max]; int i=0; cout<<"enter expresion:"; while((expr[i++]=getchar())!='\n'); expr[--i]='\0'; cout<<"the postfix expresion is:"<<expr<<"\n"; cout<<eval(expr); } Prof. Dr. Hanafy Ismail 42
Program to evaluate postfix expression using stack
• int isdigit(char symb) •{ • return(symb>='0'&&symb<='9'); •} • struct stack{ • int top; • double items[max]; • }; • struct stack s; Prof. Dr. Hanafy Ismail 43
Program to evaluate postfix expression using stack
• void push(struct stack *ps,double c) •{ • ps->items[++(ps->top)]=c; •} • double pop(struct stack *ps) •{ • return(ps->items[ps->top--]); •} Prof. Dr. Hanafy Ismail 44
Program to evaluate postfix expression using stack • • • • • • • • • • • • • • • •
double eval(char expr[]) { int i,c; double op1,op2,value; for(i=0;(c=expr[i])!='\0';i++) if(isdigit(c)) push(&s,double(c-'0')); else { op2=pop(&s); op1=pop(&s); value=oper(c,op1,op2); push(&s,value); } return(pop(&s)); }
Prof. Dr. Hanafy Ismail 45
Program to evaluate postfix expression using stack • • • • • • • • • • • • •
double oper(int c,double op1,double op2) { switch(c) { case'+':return(op1+op2); case'-':return(op1-op2); case'*':return(op1*op2); case'/':return(op1/op2); default: cout<<"error"; } return(c); }
Prof. Dr. Hanafy Ismail 46