Unit IV Stack
Unit IV Stack
Stack
Contents:
• Stacks- concept, Primitive operations, Stack Abstract
Data Type, Representation of Stacks Using Sequential
Organization, stack operations, Multiple Stacks,
Applications of Stack- Expression Evaluation and
Conversion, Polish notation and expression
conversion, Need for prefix and postfix expressions,
Postfix expression evaluation, Linked Stack and
Operations.
• Recursion- concept, variants of recursion- direct,
indirect, tail and tree, Backtracking algorithmic
strategy, use of stack in backtracking. Case Study- 4
Queens problem, Android- multiple tasks/multiple
activities and back stack.
Introduction
• A stack is a list of elements in which an element may be
inserted or deleted only at one end, called the top of the
stack.
• Stacks are sometimes known as LIFO (last in, first out)
lists.
• As the items can be added or removed only from the top
i.e. the last item to be added to a stack is the first item to
be removed.
• The two basic operations associated with stacks are:
Push: is the term used to insert an element into a stack.
Pop: is the term used to delete an element from a stack.
push operations on stack
POP operations on stack
Abstract Data Type: Stack
};
bool Stack::isEmpty() int Stack::top() / peek()
{ {
return (top < 0); if (!isEmpty()
} return a[top];
}
bool Stack::isFull()
{
return (top == MAX-
1);
}
void Stack::push(int x) int Stack::pop()
{ {
if (isFull()) if (isEmpty())
{ {
cout << "Stack Overflow"; cout << "Stack Underflow"
return -1;
} }
else
else
{
a[++top] = x;
{
} int x = a[top--];
} return x;
}
}
Stack Applications
Stacks are useful for any application requiring
LIFO storage. There are many, many of these.
• evaluating arithmetic expressions
• expression conversion
• parsing context-free languages
• function call management
• traversing trees and graphs (such as depth
first traversals)
• recursion removal
Group-C
Assignment-1
• A palindrome is a string of character that‘s the same forward
and backward. Typically, punctuation, capitalization, and spaces
are ignored. For example, ‖Poor Dan is in a droop‖ is a
palindrome, as can be seen by examining the characters ―poor
danisina droop‖ and observing that they are the same forward
and backward. One way to check for a palindrome is to reverse
the characters in the string and then compare with them the
original-in a palindrome, the sequence will be identical. Write
C++ program with functions-
1. To check whether given string is palindrome or not that uses a
stack to determine whether a string is a palindrome.
2. To remove spaces and punctuation in string, convert all the
Characters to lowercase, and then call above Palindrome
checking function to check for a palindrome
3. To print string in reverse order using stack
#define SIZE 10 Stack :: Stack()
class Stack {
{ top = -1;
private : strcpy(ST,"");
int top; }
public :
char ST[SIZE];
Stack(); int Stack :: isEmpty()
void push(char X); {
char pop(); if(top == -1)
int isEmpty(); return 1;
int isFull(); else
void convert_string(char[], char[]); return 0;
int ispalindrome(char[]); }
void reverse(char[]);
};
int Stack :: isFull() char Stack :: pop()
{ {
if(top == SIZE-1) if(!isEmpty())
return 1; {
else char X ;
return 0; X = ST[top];
} top--;
return X;
void Stack :: push(char X) }
{ }
if(!isFull())
{
top++;
ST[top] = X;
}
else
cout<<"\nStack Overflow !! Error!!";
}
/* To remove spaces and punctuation in string, convert all the
Characters to lowercase, and then call above Palindrome checking
function to check for a palindrome */
if(S.ispalindrome(Str1))
cout<<"\nGiven string is a palindrome\n";
else
cout<<"\nGiven String is not a palindrome\n“;
cout<<"\nEnter the string to be reversed : ";
cin.ignore();
cin.getline(Str,29);
cout<<"\nString entered is "<<Str;
S.reverse(Str);
return 0;
}
• cin.ignore() is a predefined function which
ignores/clears one or more characters from the
input buffer.
The cin treats a white space i.e " " , "\t" , "\n" as
delimiter character.
• cin.getline():
• It allows to specify the terminating character for
input. The default value is the newline character.
• This function reserve one character for the required
terminating character.
Example: Evaluating postfix expressions
}
else if(infix[i]==')‘)
{
/* If the current input token is ')', pop off all operators and append them to the
output string until a '(' is popped; discard the '('. */
c=pop();
while(c!='(‘)
{
postfix[j++]=c;
c=pop();
}
}
/* If the current input token is an operator, pop off all operators that have equal or
higher precedence and append them to the output string; push the operator onto
the stack. */
else if(priority(peek()) < priority(infix[i]))
push(infix[i]);
else
{
while(!isEmpty() && priority(peek()) >= priority(infix[i]))
postfix[j++]=pop();
push(Str[i]);
}
}
}
/*If the end of the input string is found, pop all operators and append
them to the output string. */
while(!isEmpty())
postfix[j++]=pop();
postfix[j]='\0';
return postfix;
}
int Stack::priority( char c)
{
int i=-1;
if(c=='+'||c=='-')
i=1;
else if(c=='*'||c=='/')
i=2;
else if(c=='^')
i=3;
else if(c==')')
i=0;
return(i);
}
void Stack::postfix_eval(char postfix[15])
{
if(isalpha(postfix[0]))
cout<<"\nInvalid Expression!";
else
{
for(int i=0;postfix[i]!='\0';i++)
{
if(isdigit(postfix[i]))
push((postfix[i])-48);
else
{
int op2=pop();
int op1=pop();
int res=cal(postfix[i],op1,op2);
push(res);
}
}
cout<<pop();
}
}
int Stack::cal(char optr,int op1,int op2)
{
int res=0;
switch(optr)
{
case '+': res=op1+op2;
break;
case '-': res=op1-op2;
break;
case '*‘: res=op1*op2;
break;
case '/': res=op1/op2;
break;
}
return res;
}
Infix to Prefix Conversion
• Expression = (A+B^C)*D+E^5
Step 1. Reverse the infix expression.
5^E+D*)C^B+A(
Step 2. Make Every '(' as ')' and every ')' as '('
5^E+D*(C^B+A)
Step 3. Convert expression to postfix form.
Expression Stack Output
5^E+D*(C^B+A) Empty -
^E+D*(C^B+A) Empty 5
E+D*(C^B+A) ^ 5
+D*(C^B+A) ^ 5E
D*(C^B+A) + 5E^
*(C^B+A) + 5E^D
(C^B+A) +* 5E^D
C^B+A) +*( 5E^D
^B+A) +*( 5E^DC
B+A) +*(^ 5E^DC
+A) +*(^ 5E^DCB
A) +*(+ 5E^DCB^
) +*(+ 5E^DCB^A
End +* 5E^DCB^A+
End Empty 5E^DCB^A+*+
• Step 4. Reverse the expression.
+*+A^BCD^E5
Prefix to Postfix conversion
return n*fact(n-1);
}
Cont..
– Indirect recursion is when a function calls a second
function which in turn calls the first function.
void g( ) {
f ( ); // indirect recursive call
}
void f ( ) {
g ( );
}
void main ( ) {
f ( );
}
Tail recursion
• A recursive function is tail recursive when recursive
call is the last thing executed by the function. For
example the following C++ function print() is tail
recursive.
// An example of tail recursive function
void print(int n)
{
if (n < 0) return;
cout << " " << n;
Portion A
Portion B
Backtracking
One strategy would be on
ncti
to try going through Ju
Portion B
Portion A of the maze.
If you get stuck before
you find your way out,
Portion A
then you "backtrack" to
the junction.