02 stacks

34
DS - DSAA ( Common Topics ) 2. Stack Introduction : In general stack is an arrangement of multiple elements kept one above the other. A new object (element) is always kept at the top. Also, only an object at the top can be removed from a stack. For example in a stack of books, one can put a book at the top of the stack of books. The book at the top can only be removed; the other end (bottom) of the stack is not accessible. Definition: A stack is an ordered collection of elements in which the elements are inserted and removed from one end. The end is called the top of the stack. The elements are retrieved in Last In First Out (LIFO) order. That’s why stack is also called a LIFO List. Stack is a dynamic structure, which can grow or shrink in size according to the operations performed on it. The figure 1 on the right shows a stack with four elements in it. The stack-top D Stack top position is indicated by the arrow. One end C of the stack is opened where the items B can be added or removed. A Fig 1 The stack top position keeps on changing with the passage of elements in the stack. Now consider that one element P is added to the stack and then two elements are removed from stack. One element M is then added to the stack. The operations are as shown in the following figures 4.2. P D D D M C C C C C B B B B B A A A A A element P Top element Top element element M is added removed removed is added Fig 2 Stack Abstract Data Type (Stack ADT) : Prepared by, Santosh Kabir. 1 of 34 2. Stack Contact No: 98336 29398 www.santoshkabirsir.com

Upload: amitfegade121

Post on 07-Dec-2015

214 views

Category:

Documents


1 download

DESCRIPTION

Stack noted

TRANSCRIPT

DS - DSAA ( Common Topics )

2. Stack

Introduction :In general stack is an arrangement of multiple elements kept one above the other. A new object (element) is always kept at the top. Also, only an object at the top can be removed from a stack. For example in a stack of books, one can put a book at the top of the stack of books. The book at the top can only be removed; the other end (bottom) of the stack is not accessible.

Definition:A stack is an ordered collection of elements in which the elements are inserted and removed from one end. The end is called the top of the stack. The elements are retrieved in Last In First Out (LIFO) order. That’s why stack is also called a LIFO List.Stack is a dynamic structure, which can grow or shrink in size according to the operations performed on it.

The figure 1 on the right shows a stack with four elements in it. The stack-top D Stack topposition is indicated by the arrow. One end Cof the stack is opened where the items Bcan be added or removed. A Fig 1

The stack top position keeps on changing with the passage of elements in the stack. Now consider that one element P is added to the stack and then two elements are removed from stack. One element M is then added to the stack. The operations are as shown in the following figures 4.2.

PD D D MC C C C CB B B B BA A A A A

element P Top element Top element element M is added removed removed is added

Fig 2Stack Abstract Data Type (Stack ADT) :The stack ADT mainly supports following three operations:Push( element ) : Add (insert) element at the top of the stack.

Input : Element ; Output: NonePop( ) : Reads and returns element at the stack top position. Stack top is moved to second last element. If stack is empty then generates error.

Input: None; Output: Top Element

Prepared by, Santosh Kabir. 1 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

DS - DSAA ( Common Topics )

Display( ) : Displays stack elements from top to bottom. If stack is empty generates

Error.Input: None ; Output : all stack elements

Also, following additional methods are also used for stack ADT.Size() : Returns number of objects on stack.

Input : None ; Output : IntegerisEmpty( ) : Returns true if stack is empty else false.

input : None ; output : integer ( rather Boolean)top( ) : Returns element at the stack top. If stack is empty generates Error. ( also, called as Peek operation. )

Input : None ; Output : Element

Implementation of stack:

Array implementation:To hold stack elements we use an Array and to keep a track of stack top we use an integer.

Implementing Push operation:The push procedure can be written as follows,

A-11. Input an element to add to stack

2. If stack is full

Display error OR throw exception

3. Else

Increment stack top

Store element at the new stack top position

Implementing Pop operation:The pop procedure can be written as follows,

A-21. If the stack is empty

Display error message OR throw exception

2. Else

Read a stack-top element

Decrement stack-top

Return the stack-top element

The test can be performed before every pop operation to check whether the stack is empty.

Peek operation:Reading a stack top value is called peep operation of a stack. Stack is not affected in this operation.

A-31. If the stack is empty

Display error message OR throw exception

Prepared by, Santosh Kabir. 2 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

DS - DSAA ( Common Topics )

2. Else

Read a stack-top element

Return the stack-top element

Checking for Exceptional conditions:1) Stack overflow: This will occur when stack is full i.e. when no more elements can be added to the stack. This condition must be checked before pushing element to the stack.2) Empty stack: This will occur when program code tries to read the stack and stack has no elements in it. The condition must be checked before popping element from stack or reading elements from the stack.In our program we will display messages for these error conditions.

Program : ( Array implementation of Stack )#include<stdio.h>#include<conio.h>struct Stack{

int a[5]; int top;};

// Global variable for stackstruct Stack stak;// functions prototypes for stack operationsvoid Push( int v );int Pop(void);void PrintStack(void);int Peek(void);int IsEmpty(void);int IsFull(void);

void main(){ int v, opt;

clrscr(); // Initialize stack stak.top = -1; printf("Stack Operations\n"); while( 1 ) { printf("Push...1\n"); printf("Pop....2\n");

printf("Print..3\n"); printf("Peek...4\n");

printf("Exit...5\n"); printf("Enter option :"); scanf("%d", &opt );

Prepared by, Santosh Kabir. 3 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

DS - DSAA ( Common Topics )

switch( opt ) { case 1: printf("Enter a value to push:"); scanf("%d", &v ); Push( v ); break; case 2 :if( ! IsEmpty() ) { v = Pop(); printf("Poped value=%d\n", v ); } else printf("Stack is empty\n"); break; case 3 : PrintStack();

break; case 4: if( ! IsEmpty() ) { v = Peek(); printf("Top value :%d\n", v ); } else printf("Stack is empty\n"); break; case 5 : return; // stop main() i.e. end program } } getch();}

void Push( int v ){

if( ! IsFull() ) { stak.top++; stak.a[ stak.top ] = v; } else printf("Stack is full\n");}int Pop(){

int v; v = stak.a[ stak.top ]; stak.top--; return v;}

Prepared by, Santosh Kabir. 4 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

DS - DSAA ( Common Topics )

void PrintStack(){

int i;if( ! IsEmpty() )

{ printf("Stack values\n"); for( i=stak.top; i>=0; i-- ) printf("%d\t", stak.a[i] ); printf("\n"); } else printf("Stack is Empty\n");}int Peek(){

int v; v = stak.a[ stak.top ]; return v;}int IsEmpty(){

if( stak.top == -1 ) return 1; else return 0;}int IsFull(){

if( stak.top == 5 ) return 1;

else return 0;}

Stack Applications:

Checking valid parenthesis in a mathematical expression: Consider a mathematical expression that includes several sets of nested parenthesis. Lets write a procedure to check the parentheses are valid or not. We have to check that there are equal numbers of left and right parentheses and every closing parenthesis is preceded by matching opening parenthesis. The algorithm works as follows,

Input: A string consisting of an expression

Output : Return 1 (i.e true) for valid and 0 (i.e. false) for invalid expression

1. Create an empty stack.

2. Initialize a flag var. ‘valid’ to false.

Prepared by, Santosh Kabir. 5 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

DS - DSAA ( Common Topics )

3. While not end of the string repeat …

a. Read a character from the string into var. ‘symb’

b. If symb is open parenthesis

Push it to the stack

c. If it’s a close parenthesis

If stack is not empty

Compare the symb and stack top symbol

If mismatch found then

make valid = false and stop loop

Else

Make valid=false and stop the loop

d. Advance to next character.

4. If stack has symbols (after end of string)

Make valid false

5. return value in valid

Program :

#include<stdio.h>#include<conio.h>#include<string.h>struct Stack // Stack of characters

{char a[5]; // char array

int top;};

// Global variable for stackstruct Stack stak;

// functions prototypesvoid Push( char );char Pop(void);int IsEmpty(void);int IsValid( char []);int Match( char , char );

void main(){ int v; char expr[50];

clrscr(); printf("Enter an expression :"); gets( expr ); v = IsValid( expr ); if( v == 1 ) printf("Expression is valid");

Prepared by, Santosh Kabir. 6 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

DS - DSAA ( Common Topics )

else printf("Invalid Expression");

getch();}

int IsValid( char a[ ] ) // fn to check valid expression

{int valid = 1; // assume it’s a valid expr.

int i, len;char symb, ch;

// Initialize empty stack stak.top = -1; len = strlen(a);

for( i=0; i< len; i++) //while not end of given expr.

{symb = a[i]; // Read ith char.

if(symb == '(' || symb == '[' || symb == '{') Push( symb ); else if(symb == ')' || symb == ']' || symb == '}') { if(IsEmpty()) { valid = 0; break; } else { ch = Pop(); if(! Match(symb, ch)) { valid = 0; break; } } } // else if end

} // for ends

if( ! IsEmpty()) // If stack has elements after end of expr.

valid = 0;

return valid;}

Prepared by, Santosh Kabir. 7 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

DS - DSAA ( Common Topics )

int Match(char s, char c){

if(s==')' && c == '(')return 1;

else if(s==']' && c == '[')return 1;

else if(s=='}' && c=='{')return 1;

else return 0;}void Push( char v ){ stak.top++; stak.a[ stak.top ] = v;}char Pop(){

char v; v = stak.a[ stak.top ]; stak.top--; return v;}int IsEmpty(){

if( stak.top == -1 ) return 1; else return 0;}

Infix, Postfix and Prefix expressions:There are three different ways for writing a arithmetic expressions. These depend on the order in which operators and operands are arranged in the expression.

Infix Expressions : In this notation an operator lies between the two operands. This is a common notation ( that we use to write expressions). i.e. Operand1 operator Operand2e..g A+B, A- B etc.Postfix Expressions : In this notation Operator lies after the two operands.i.e. Operand1 Operand2 Operator

A B + , A B - are postfix expression.+AB called prefix expression

Prefix Expressions : In this notation Operator lies before the two operands.i.e. Operator Operand1 Operand2

Prepared by, Santosh Kabir. 8 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

DS - DSAA ( Common Topics )

+ A B , - A B are Prefix expressions.

Note : See details in our class note-book.

Infix to Postfix conversion:Consider an infix expression A+B*C. While converting the expression into postfix notation we have to take care of the precedence of the operators existing in the expression. Following stages will occur in the conversion,

A + B * C Given infix expressionA + (BC*) Convert the multiplication firstA(BC*) + Convert the addition. (BC*) treated as single operand.ABC*+ Write a final postfix expression.

Thus, operations with the highest precedence operators are converted first and after the portion of the expression is converted to postfix it is to be treated as a single operand.

Consider the following example in which braces are used.( A+ B ) * C Given infix expression(AB+) * C Convert the addition. (AB+)C* Convert the multiplication. (AB+) is treated as single operand.AB+C* Final postfix expression.

In our further discussion we will consider five operands: addition (+), subtraction (-), multiplication (*), division (/) and exponentiation($). The precedence will be as follows,

1.Exponentiation2.Multiplication/Division3.Addition/Subtraction

Braces can be used to override the default precedence.

Note : Same expression written in any notation should have same meaning and same final value..

Evaluating a Postfix expression:

Consider a postfix expression, 4 5 + 6 2 - *Each operator in a postfix string refers to the previous two operands. One of these operands can itself be the result of applying a previous operator.Following algorithm evaluates an expression in postfix using the above method,

A-31. Input a Postfix expression string

2. Create an empty stack.

3. While not end of an input string repeat following steps

a Read a character from string

b If the character is an operand

i. Push the character (operand) to stack

c Else if its an operator

i. Pop value from stack as a Second operand

Prepared by, Santosh Kabir. 9 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

DS - DSAA ( Common Topics )

ii. Pop next value from stack as a First operand

iii. Get the result of applying the operator on the two operands

iv. Push the result on the stack

4. Advance to the next character and go to 3

5. Pop value from stack and return it.

Following table shows status of each entity (stack, symbol, operand1, operand2 and result) when the above algorithm is applied to evaluate the given postfix expression.

( Refer the postfix expression written above : 4 5 + 6 2 - * )

Symbol Operand1 Operand2 Value Stack4 45 4, 5+ 4 5 9 96 4 5 9 9, 62 4 5 9 9, 6, 2- 6 2 4 9, 4* 9 4 36 36

See the program below.Following code segment presents a function EvalPostfix() that evaluates the given postfix expression and returns a value of the expression. The function Operate() returns the result of applying the current operator on the two operands.

Program :

#include<stdio.h>#include<conio.h>#include<math.h>#include<string.h>struct Stack // define stack for float values{

float a[10]; int top;};

// Global variable for stackstruct Stack stak;

// functions prototypes for stack operationsvoid Push( float v);float Pop( );int IsEmpty( );

// function prototypes for Postfix evaluation

Prepared by, Santosh Kabir. 10 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

DS - DSAA ( Common Topics )

float EvalPostfix( char [] );float Operate( char oper, float opnd1, float opnd2 );

void Push( float v ){ stak.top++; stak.a[ stak.top ] = v;}float Pop(){

int v; v = stak.a[ stak.top ]; stak.top--; return v;}

float EvalPostfix( char expr[] ){

char ch; int i, len;

float opnd1, opnd2,val; struct Stack stak;

stak.top = -1;

len = strlen( expr );

for(i=0; i<len; i++ ){

ch = expr[i];if( ch>='0' && ch<='9' ){

Push( ch - '0' );}else{

opnd2 = Pop(); // Stack-top item is second operandopnd1 = Pop();val = Operate( ch, opnd1, opnd2);Push( val); // push the result to stack

}}val = Pop(); // Pop the final value i.e. value of given expr.return val;

}

float Operate(char ch, float opnd1, float opnd2){

// Operates on opnd1 and opnd2 according to the ch i.e operatorswitch(ch)

Prepared by, Santosh Kabir. 11 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

DS - DSAA ( Common Topics )

{case '+' : return(opnd1+opnd2);case '-' : return(opnd1-opnd2);case '/' : return(opnd1/opnd2);case '*' : return(opnd1*opnd2);case '$' : return( ( float)pow(opnd1,opnd2));default : printf("\n\nInvalid operator ...%c\n" , ch);return 0;

}}

void main(){

char s[30]; float v; clrscr(); printf("Enter Postfix expression :"); gets( s ); v = EvalPostfix( s ); printf("Value = %f", v ); getch();}

Evaluation of Prefix expression:

Consider a prefix expression, - + 5 * 7 3 / 6 2Each operator in a prefix string refers to the next two operands. One of these operands can itself be the result of applying a previous operator.Following algorithm evaluates a prefix expression :

A-41. Input a Prefix expression (as a string)

2. Create an empty stack.

3. Find length of the string. (say len)

4. Go to the end of the string

5. While beginning of input string is not reached, repeat following steps

a Read a character from the string

b If the character is an operand

Push the character (operand )to stack

c Else

i. Pop the first value from stack as first operand

ii. Pop the next value from stack as second operand

iii. Get the result of applying the operator on the two operands

iv. Push the result on the stack

6. Advance to the previous character and go to 5

7. Return the last popped value

Prepared by, Santosh Kabir. 12 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

DS - DSAA ( Common Topics )

Following table shows status of each variable (stack, symbol, oper1, oper2 and value) when the above algorithm is applied to evaluate the given prefix expression.( Refer the prefix expression written above : - + 5 * 7 3 / 6 2 )

Symbol Oper1 Oper2 Value Stack2 26 2 6/ 6 2 3 33 6 2 3 3 37 6 2 3 3 3 7* 7 3 21 3 215 7 3 21 3 21 5+ 5 21 26 3 26- 26 3 23 23

// Function to evaluate Prefix expr.float EvalPrefix( char expr[] ){

char ch; int i, len;

float opnd1, opnd2,val; struct Stack stak;

stak.top = -1; len = strlen( expr );

for( i=len-1; i>=0; i-- ) // read chars from end to beginning of string{

ch = expr[i];if( ch>='0' && ch<='9' ){

Push( ch - '0' );}else{

opnd1 = Pop(); // Stack-top item is 1st operandopnd2 = Pop();val = Operate( ch, opnd1, opnd2);Push( val); // push the result to stack

}}val = Pop(); // Pop the final value i.e. value of given expr.return val;

}

Converting an Infix expression into Postfix expression:

Prepared by, Santosh Kabir. 13 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

DS - DSAA ( Common Topics )

Here, we will input an infix expression as a string and the postfix expression will be a string generated by applying the rules of postfix expression and rules of precedence. Every operand is directly added to the postfix string and the operators (also the parentheses) are pushed onto the stack or popped from the stack by checking the precedence rules.The algorithm for conversion of Infix expression to Postfix is as follows.

Input : Infix expression as a string

Output : Returns Postfix expression string

Create an empty stack to hold char values.

1. While not end of infix string

a. Read a character from infix string

b. If the character is operand

Add the char. into the postfix string

c. If the character is open parenthesis

Push it on the stack

d. If the character is operator

If stack is Not empty

While stack has operators with same or higher precedence than the character

Pop the operators from stack and put them in postfix expr. String

Push the current character (i.e. operator) to the stack.

e. If the character is a close parenthesis

Till open parenthesis is encountered

Pop operators from stack and put in postfix expr. string

2. Advance to next character. Go to step 1

3. If stack is not empty

Pop all the symbols from stack and put in postfix expr. string

4. Return postfix expr. string

Program to Infix to Postfix conversion. It consists of a function InfixToPost() that has two parameters : first is the input infix string and the second is empty string that will hold the resultant Postfix expression.

Program :

#include<stdio.h>#include<conio.h>#include<math.h>#include<string.h>

struct Stack // define stack for characters{

char a[10]; int top;};

// Global variable for stack

Prepared by, Santosh Kabir. 14 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

DS - DSAA ( Common Topics )

struct Stack stak;

// functions prototypes for stack operationsvoid Push( char v);char Pop(void);int IsEmpty( void );

// function prototypes for Infix to Postfix conversionvoid InfixToPost( char [], char [] );int Priority( char ch );int IsOperand( char ch );

void Push( char v ){ stak.top++; stak.a[ stak.top ] = v;}char Pop(){

char v; v = stak.a[ stak.top ]; stak.top--; return v;}int IsEmpty(){

if( stak.top == -1 ) return 1; else return 0;}void InfixToPost(char expr[], char res[] ){

int len = strlen(expr);char ch, opr;

int i, j=0;int f= 0; //Used as flag variablestruct Stack stak; // create empty stack

stak.top = -1;

for( i=0; i< len; i++){

ch = expr[i]; // read ith char.

if( ch ==' ' ) // Neglect spaces and tab chars

continue;if( IsOperand( ch ) ) //operand

{

Prepared by, Santosh Kabir. 15 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

DS - DSAA ( Common Topics )

res[j] = ch;j++;

}else if( ch == '(' ) // Open braces{

Push ( ch ) ;}else if ( ch == ')' ) // close braces{

opr = Pop( ) ;while ( ( opr ) != '(' ){

res[j] = opr ;j++ ;opr = Pop( ) ;

}}

else // operator{

if ( ! IsEmpty() ){

f = 0; //.. initialize flag to 0opr = Pop() ;while ( Priority ( opr ) >= Priority (ch) ){

res[j] = opr;j++;if( IsEmpty() ){

f = 1; //.. change flag to 1 .. to indicate stack is now emptybreak;

}opr = Pop();

}if( f == 0 ){

Push( opr );}

}Push( ch ) ; // .. push latest char. to stack

} } /* for loop ends */

// Read remaining all operators from stackwhile ( !IsEmpty() ){

opr = Pop ( ) ;res[j] = opr ;j++ ;

Prepared by, Santosh Kabir. 16 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

DS - DSAA ( Common Topics )

} res[j] = '\0'; // end the resultant string}

/* returns the priority of an operator (as a number) */int Priority ( char c ){

if ( c == '$' ) // Highest prio.return 3 ;

if ( c == '*' || c == '/' || c == '%' )return 2 ;

if ( c == '+' || c == '-' )return 1 ;

else // Others, lowest prio.return 0 ;

}int IsOperand( char ch ){

// if char is a Letter or Digit return 1 i.e. trueif( (ch>='a' && ch <='z') || (ch >='A' && ch<='Z') )

return 1; else if( ch >='0' && ch <= '9') return 1; else return 0;}

void main(){

char s[30], r[30]; clrscr(); printf("Enter a Infix expression :"); gets( s ); InfixToPost( s , r ); printf("Postfix Expr. = %s", r ); getch();}

Infix to Prefix conversion :

The algorithm for conversion of Infix expression to Postfix is as follows. The algorithm works very similar to the Infix to Postfix conversion method. Here, first the given infix expression string is reversed. When nearly same algorithm is applied to the reversed string we get a Prefix expression string in reversed fashion. We again reverse this string to get the proper Prefix expression. (Major variations from the previous algo. Are shown with italic letters.)

Prepared by, Santosh Kabir. 17 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

DS - DSAA ( Common Topics )

Input :Infix expression as a string

Output :Returns Prefix expression string

Create an empty stack to hold char values.

Reverse the given Infix string

1. While not end of infix string

a. Read character from infix string

b. If the character is operand

Write into the prefix string

c. If the character is close parenthesis

Push it to the stack

d. If the character is operator

If stack is Not empty

While stack has operators with higher or same precedence than the character

Pop the operators from stack and put them in prefix string.

Push the character to the stack

e. If the character a open parenthesis

Till close parenthesis is encountered

Pop operators from stack and put in prefix string.

2. Advance to next character. Go to step 1.

3. If stack is not empty

Pop all the symbols from stack and put in prefix string.

4. Reverse the string for prefix expression to get the actual Prefix expression.

5. Return Prefix expression.

Following function infixToPre() takes infix expression in the form of a string argument and stores the prefix string in second parameter. void InfixToPre(char expr[], char res[] ){

char ch, opr; int i, j=0, k; int len = strlen(expr);

int f= 0; //Used as flag variablestruct Stack stak; // create empty stack

stak.top = -1;

for( i=len-1; i>=0; i--){

ch = expr[i]; // read ith char.if( ch ==' ' )// Neglect spaces and tab chars

continue; if( IsOperand( ch ) ) //operand

{res[j] = ch;j++;

}else if( ch == ')' ) // Close braces{

Prepared by, Santosh Kabir. 18 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

DS - DSAA ( Common Topics )

Push ( ch ) ;}else if ( ch == '(' ) // Open braces{

opr = Pop( ) ;while ( ( opr ) != ')' ){

res[j] = opr ;j++ ;opr = Pop( ) ;

}}

else // operator{

if ( ! IsEmpty() ){

f = 0; //.. initialize flag to 0opr = Pop() ;while ( Priority ( opr ) >= Priority (ch) ){

res[j] = opr;j++;if( IsEmpty() ){

f = 1; //.. change flag to 1.. to indicate stack is now emptybreak;

}opr = Pop();

}if( f == 0 ){

Push( opr );}

}Push( ch ) ;

} } /* for loop ends */

// Read remaining all operators from stackwhile ( !IsEmpty() ){

opr = Pop ( ) ;res[j] = opr ;j++ ;

} res[j] = '\0'; // end the resultant string len = strlen( res ); // reverse the resultant string for( i=0, j=len-1; i<len/2; i++,j--) { char temp = res[i]; res[i] = res[j]; res[j] = temp; }}

Prepared by, Santosh Kabir. 19 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

These notes are also available at :

www.santoshkabirsir.com

DS - DSAA ( Common Topics )

Implementing two stacks in a single array :For implementing two stacks in a single array we need two stack-top variables to point to two different stacks. In this case we assume one of the stack starts from the beginning of the array and the other starts from the end of the array. That is in the case of first stack the stack pointer will be initialized to –1 (to indicate the stack is empty) and will increment on every push operation. Similarly for the other stack the stack pointer will be initialized to the end of the array (size of the array) and decrements on every push operation. One has to take care that the two stack elements should not overwrite each other.

The following figure shows an array with size 8. The two stacks initialized as empty stacks.

Stack1 Stack2

a[0] a[1] … a[7]

top1 top2

The following figure shows the stacks with some elements. The first stack holds 4 values and the second holds 2 elements. Hence, the two stack-tops are 3 and 6 (top1=3 and top2=6) respectively.

a[0] a[1] … a[7]

top1 top2

Following code shows a program for implementing two stack in a single array. All the functions need the stack number on which the operation is to be done. For this the functions have a stack number as one of its arguments. Checking for empty stack(stack underflow), Push and Pop operations are defined in the class,

#include<stdio.h>#include<conio.h>#define Size 8struct Stack{

int a[Size]; int top1, top2;};

// Global variable for stackstruct Stack stak;

Prepared by, Santosh Kabir. 20 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

-1 8

15 25 10 12 35 25

3 6

DS - DSAA ( Common Topics )

// functions prototypes for stack operationsvoid Push( int v, int n);int Pop( int n);void PrintStack( int n );int Peep( int n );int IsEmpty( int n );int IsFull( int n );

void main(){ int v, n, opt;

clrscr(); // Initialize stacks stak.top1 = -1;

stak.top2 = Size; printf("Stack Operations\n"); while( 1 ) { printf("Push...1\n"); printf("Pop....2\n");

printf("Print..3\n"); printf("Peep...4\n");

printf("Exit...5\n"); printf("Enter option :"); scanf("%d", &opt ); switch( opt ) { case 1: printf("Enter a value to push:"); scanf("%d", &v ); printf("Enter stack no. :"); scanf("%d", &n ); Push( v , n ); break; case 2 : printf("Enter stack no. :"); scanf("%d", &n ); if( ! IsEmpty(n) ) { v = Pop( n ); printf("Poped value=%d\n", v ); } else printf("Stack is empty\n");

break;

case 3 : printf("Enter stack no. :"); scanf("%d", &n ); PrintStack( n ); break;

Prepared by, Santosh Kabir. 21 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

DS - DSAA ( Common Topics )

case 4: printf("Enter stack no. :"); scanf("%d", &n ); if( ! IsEmpty(n) ) { v = Peep( n ); printf("Top value :%d\n", v ); } else printf("Stack is empty\n"); break;

case 5 : return; // stop main() i.e. end program } } getch();}void Push( int v, int n ){

if( ! IsFull( n ) ) { if( n == 1 ) { stak.top1++; stak.a[ stak.top1 ] = v; } else { stak.top2--; stak.a[ stak.top2 ] = v; } } else printf("Stack is full\n");}int Pop( int n){

int v; if( n == 1 ) { v = stak.a[ stak.top1 ]; stak.top1--; } else { v = stak.a[ stak.top2 ]; stak.top2++; } return v;}

Prepared by, Santosh Kabir. 22 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

DS - DSAA ( Common Topics )

void PrintStack( int n){

int i;if( ! IsEmpty(n) )

{ printf("Stack values\n");

if( n == 1 ) for( i=stak.top1; i>=0; i-- ) printf("%d\t", stak.a[i] ); else

for( i=stak.top2; i<8; i++ ) printf("%d\t", stak.a[i] );

printf("\n"); } else printf("Stack is Empty\n");}int Peep( int n){

int v; if( n == 1 ) v = stak.a[ stak.top1 ]; else v = stak.a[ stak.top2 ]; return v;}int IsEmpty(int n){ if( n ==1 )

{ if( stak.top1 == -1 ) return 1; else return 0; } else

{ if( stak.top2 == 8 ) return 1; else return 0; }

}int IsFull(){

if( stak.top2 - stak.top1 == 1 ) return 1; else return 0;}

Prepared by, Santosh Kabir. 23 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

DS - DSAA ( Common Topics )

Linked list implementation of stack:Stack is LIFO list. The last element added to the stack (push operation) is

supposed to be at the top of the stack. Also, an element is always removed from

the top of the stack (pop operation).

We can use a linked list ( singly linked list) as a stack.

Adding element at the end of List is a Push() operation.

Removing last element from the list is a Pop operation.

Also, displaying stack corresponds to displaying entire list from last to first

element. Push operation – Adding a new item in the linked list can be treated as pushing a new element to

the stack. The pointer for the new item (pointer to the new node in the list)

indicates the top of the stack.

Algo.

1. Input the value

2. Create a new node

3. Put data in the new node

4. If stack is empty (i.e. List is empty)

a. New node holds null link

5. Else

a. New node refers to refer to current top element.

6. Update top to refer to new node.

Pop operation –Removing a last item in the list is equivalent to pop operation of a stack. When

the last item is popped the stack, top refers to the second last item in the list.

Algo:

1. Read the value from stack top

2. Update top to refer to the previous node.

3. Return the value read from the old top.

Following figure shows pushing three numbers 10, 20 and 30 to the stack and

popping two elements.

push(10)

push(20)

push(30)

N=pop()

Prepared by, Santosh Kabir. 24 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

10 NULL

10 NULL 20

10 NULL 20 30

10 NULL 20 N = 30

DS - DSAA ( Common Topics )

N=pop()

Program :#include<stdio.h>

#include<conio.h>

#include<alloc.h>

struct Node

{

int data;

struct Node *prev;

};

struct Node *top=NULL;

void Push( int n );

int Pop( void );

void Display( void );

int Peek(void);

int IsEmpty(void);

void main()

{

int n;

int opt;

clrscr();

printf("Stack using Linked List\n");

while(1)

{

printf("Push ..... 1\n");

printf("Pop ...... 2\n");

printf("Peek ..... 3\n");

printf("Display .. 4\n");

printf("Exit ..... 5\n");

printf("Enter option :");

scanf("%d", &opt );

switch( opt )

{

case 1: printf("Enter a value :");

scanf("%d", &n);

Push( n );

break;

Prepared by, Santosh Kabir. 25 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

10 NULL N = 20

DS - DSAA ( Common Topics )

case 2: if( ! IsEmpty() )

{

n = Pop();

printf("Popped value =%d\n", n);

}

else

printf("Stack is empty\n");

break;

case 3: if( ! IsEmpty() )

{

n = Peek();

printf("Stack top value =%d\n", n);

}

else

printf("Stack is empty\n");

break;

case 4: Display( );

break;

case 5: return;

}

}

getch();

}

int IsEmpty()

{

if( top == NULL )

return 1;

else

return 0;

}

void Push( int v )

{

struct Node *nw;

nw = (struct Node*) malloc( sizeof(struct Node) );

nw->data = v;

nw->prev = top;

Prepared by, Santosh Kabir. 26 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

DS - DSAA ( Common Topics )

top = nw;

}

int Pop()

{

int v;

v = top->data;

top = top->prev;

return v;

}

int Peek()

{

int v;

v = top->data;

return v;

}

void Display()

{

struct Node *r;

if( IsEmpty() )

printf("Stack is empty\n");

else

{

r = top;

printf("Stack element...\n");

while( r != NULL )

{

printf("%d\t", r->data);

r = r->prev;

}

printf("\n");

}

}

Advantages of using linked implementation are as follows,

No space is pre-allocated for the stack. Thus no limitation on stack size.

The stack can grow and shrink in size during program execution. During push,

memory is allocated for a new node and in the pop() the memory occupied by

the element is freed.

Disadvantage is that with each element an extra space is needed for a reference

field.Some more functions for Stack Applications :Prepared by, Santosh Kabir. 27 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

DS - DSAA ( Common Topics )

Postfix to Prefix Conversion:Algo:

Input : A Postfix expression

Output : A prefix expression

1. Create an empty stack for holding strings

2. For each character in the postfix string, do

a. Read character

b. If a character is operand then

i. push it on the stack

c. Else

i. Pop string from stack say s1

ii. Pop next String from stack say s2

iii. Make new string by putting together the operator, second string(s2) and

the first string (s1)

iv. Push the new string to the stack

3. Pop the last string from stack

4. Return the string (prefix expr)

Program :

In the following program, function PostfixToPre() does the task of converting Postfix string to Prefix.

#include<stdio.h>#include<conio.h>#include<math.h>#include<string.h>struct Stack // define stack for characters{

char a[15][30]; int top;};// Global variable for stackstruct Stack stak;// functions prototypes for stack operationsvoid Push( char v[]);char* Pop(void);int IsEmpty( void );// function prototypes for Prefix to Postfix conversionvoid PostfixToPre( char [], char [] );int IsOperand( char ch );

void Push( char v[] ){ stak.top++; strcpy( stak.a[ stak.top ],v );}char * Pop(){

Prepared by, Santosh Kabir. 28 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

DS - DSAA ( Common Topics )

char v[20]; strcpy( v, stak.a[ stak.top ] ); stak.top--; return v;}int IsEmpty(){

if( stak.top == -1 ) return 1; else return 0;}

void PostfixToPre( char expr[], char res[]){

int i, j;int len = strlen( expr );struct Stack stak;

stak.top = -1;for( i=0; i<len; i++ ){

char ch = expr[ i ]; // read ith char.

char a[2]; a[0] = ch; a[1] ='\0'; // store the char. as string

if( IsOperand(ch) ) // for operand{

Push( a ); }

else // for operator{

char nw[20]=""; char s1[20]="",s2[20]="";

strcpy(s1, Pop());strcpy(s2, Pop());strcat(nw,a);

strcat(nw, s2); strcat(nw, s1);

Push( nw );}

}strcpy( res, Pop() );

}

int IsOperand( char ch ){

Prepared by, Santosh Kabir. 29 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

DS - DSAA ( Common Topics )

// if char is a Letter or Digit return 1 i.e. trueif( (ch>='a' && ch <='z') || (ch >='A' && ch<='Z') )

return 1; else if( ch >='0' && ch <= '9') return 1; else return 0;}void main(){

char s[30], r[30]; clrscr()

printf("Enter a Postfix expression :"); gets( s ); PostfixToPre( s , r ); printf("Prefix Expr. = %s", r ); getch();}

Prefix to Postfix Conversion:

Algo:

Input : A Prefix expression

Output : A Postfix expression

1. Create an empty stack for holding strings

2. Set index at the end of input (Prefix) string

3. Till beginning of string is reached, do

a. Read character

b. If a character is operand

i. push it to the stack

c. Else

i. Pop string from stack say s1

ii. Pop next String from stack say s2

iii. Make new string by putting together the operator, second string(s2) and

the first string (s1)

iv. Push the new string to the stack

4. Pop the last string from stack

5. Reverse the popped String

6. Return the string (Postfix expr)

Following code presents function to convert Prefix expression to Postfix expression. ( Remaining program is same as Postfix to Prefix conversion )

void PrefixToPost( char expr[], char res[]){

Prepared by, Santosh Kabir. 30 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

These notes are also available at :

www.santoshkabirsir.com

DS - DSAA ( Common Topics )

int i, j;int len = strlen( expr );struct Stack stak;

stak.top = -1;

for( i=len-1; i >=0; i--){

char ch = expr[ i ]; // read ith char.

char a[2]; a[0] = ch; a[1] ='\0'; // store the char. as string

if( IsOperand(ch) ) // for operand{

Push( a ); }

else // for operator{

char nw[20]=""; char s1[20]="",s2[20]="";

strcpy(s1, Pop());strcpy(s2, Pop());strcat(nw,a);

strcat(nw, s2); strcat(nw, s1);

Push( nw );}

}strcpy( res, Pop() );

for( i=0, j=len-1; i<len/2; i++, j--) { char temp = res[i]; res[i] = res[j]; res[j] = temp; }}

====000====

Prepared by, Santosh Kabir. 31 of 31 2. StackContact No: 98336 29398 www.santoshkabirsir.com

Classes Conducted by Santosh Kabir sir,

FE Sem II SPA All Branches

SE Sem III OOPM(Java) Comp / IT

DS / DSAA Comp / IT

SE Sem IV Web Programming IT(WP)

Mobile : 98336 29398www.santoshkabirsir.com