1186233570531_stack

26
Lecture Notes: 4 STACK ADT INTRODUCTION As an abstract data type, the stack is a container and has two basic operations:  pus h and pop. Push adds a given node to the top of the stac k leaving pre vio us nodes  below. Pop removes and returns the current top node of the stack. A frequ ently used metaphor is the idea of a stack of plates in a spring loaded cafeteria stack. In such a stack, only the top plate is visible and accessible to the user, all other plates remain hidden. As new plates are added (pushed), each new plate becomes the top of the stack, and hides each plate below. As plate s are remov ed (popped) from the stack , they can be used, and second plate becomes the top of the stack. Two important principles are illustrated by this metaphor, the Last In First Out principle is one. The second is that the contents of the stack are hidden. Only the top plate is visible, so to see what is on the third plate, the first and second plates will have to be removed. DEFINITION A stack is a list in which all insertions and deletions are made at one end, called the top. The last element to be inserted into the stack will be the first to be removed. Thus stacks are referred to as Last in First out (LIFO) lists. . The data structure of stack maybe compared to its real world counterparts such as a stack of books in a library  Due to its property of LIFO, a stack grows in one direction (top) when elements are added to it. Conversely, a stack reduces in size or ‘shrinks’ only from one side when elements are removed from it. Addition to a stack is termed as ‘Push’ and deletion from a stack is termed as ‘Pop’.Real time Example of Stack: Pile of books, blocks, boxes etc.  Notes Compiled for M.S Software Engg A & B Batch - 1 -

Upload: anandan0

Post on 10-Apr-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

8/8/2019 1186233570531_STACK

http://slidepdf.com/reader/full/1186233570531stack 1/26

Lecture Notes: 4

STACK ADT

INTRODUCTION

As an abstract data type, the stack is a container and has two basic operations: push and pop. Push adds a given node to the top of the stack leaving previous nodes

 below. Pop removes and returns the current top node of the stack. A frequently usedmetaphor is the idea of a stack of plates in a spring loaded cafeteria stack. In such a stack,

only the top plate is visible and accessible to the user, all other plates remain hidden. As

new plates are added (pushed), each new plate becomes the top of the stack, and hideseach plate below. As plates are removed (popped) from the stack, they can be used, and

second plate becomes the top of the stack. Two important principles are illustrated by this

metaphor, the Last In First Out principle is one. The second is that the contents of thestack are hidden. Only the top plate is visible, so to see what is on the third plate, the first

and second plates will have to be removed.

DEFINITION

A stack is a list in which all insertions and deletions are made at one end, called

the top. The last element to be inserted into the stack will be the first to be removed. Thusstacks are referred to as Last in First out (LIFO) lists. . The data structure of stack maybe

compared to its real world counterparts such as a stack of books in a library

 

Due to its property of LIFO, a stack grows in one direction (top) when elements

are added to it. Conversely, a stack reduces in size or ‘shrinks’ only from one side whenelements are removed from it. Addition to a stack is termed as ‘Push’ and deletion from a

stack is termed as ‘Pop’.Real time Example of Stack: Pile of books, blocks, boxes etc.

 Notes Compiled for M.S Software Engg A & B Batch - 1 -

8/8/2019 1186233570531_STACK

http://slidepdf.com/reader/full/1186233570531stack 2/26

Lecture Notes: 4

STACK MODEL—LIFO

Top

• The first item put on the stack is on the bottom of the stack.

• All items added to the stack are placed on top of the previous item.

• The last item put on the stack is on the top of the stack.

• The last inserted data will be get deleted from stack first so it is calledas Last-In-First-Out (LIFO).

Uses of ADT Stack 

• Depth first search / backtracking

• Evaluating postfix expressions

• Converting infix to postfix

• Function calls (runtime stack)

• Recursion

BASIC OPERATIONS OF STACK 

Push: Insertion of elements into the stack.

Pop: Deleting elements from the stack.

• A Stack class should have the following methods:

 push(item) //Push an item onto the stack  pop( ) //Pop an item off the stack  

top( ) //Return value of top item

empty() //Return true if stack is empty.

 Notes Compiled for M.S Software Engg A & B Batch - 2 -

 

Orange

Apple

Mango

8/8/2019 1186233570531_STACK

http://slidepdf.com/reader/full/1186233570531stack 3/26

Lecture Notes: 4

PUSH

POP

IMPLEMENTATION OF STACK 

Stack can be implemented using the following structures

• Array

When a stack is implemented as an array, it is of finite size, that is, it has a

maximum limit to which data maybe added to it. Also, elements of the stack arestored side-by-side in the memory.

• Linked List

When implemented as a linked list, the stack does not have an upper limit for thenumber of elements that can be added to it and supports dynamic memoryallocation.

Stack implementation using array

int StackArray[10]; // StackArray can contain up to 10 numbers

int top=-1; // index of the top element of the stack i.e, top= -1 is used to

 Notes Compiled for M.S Software Engg A & B Batch - 3 -

8/8/2019 1186233570531_STACK

http://slidepdf.com/reader/full/1186233570531stack 4/26

Lecture Notes: 4

indicate an empty stack 

PUSH Operation

void Push(int elem) // Push operation

{

top++; // Increment the top pointer  StackArray[top] = elem; // Insert the data in the top position

}

  Top = -1 ===> Empty stack 

0 1 2 3 4 5 6 7 8 9

For example push(10)

Increment the top so Top = -1+1 =0

0 1 2 3 4 5 6 7 8 9

Top

Insert the data into the stack 

10

0 1 2 3 4 5 6 7 8 9

Top

push(20)

Increment the top so Top = 0+1 =1

10

0 1 2 3 4 5 6 7 8 9

Top

Insert the data into the stack 

10 200 1 2 3 4 5 6 7 8 9

Top

To push data into the stack check whether the top is less than maximum size of 

array declared if so increment the top pointer and insert the data into the stack in the array

 Notes Compiled for M.S Software Engg A & B Batch - 4 -

8/8/2019 1186233570531_STACK

http://slidepdf.com/reader/full/1186233570531stack 5/26

Lecture Notes: 4

index pointed by the top pointer. Otherwise if top is greater than the maximum size print

stack is full.

Stack Overflow Condition

Once if the stack is full and again data is inserted data into the stack it is termed asStack Overflow condition. For example here maximum size of the stack is 10 and we

have inserted 10 elements again if you try to insert data into the stack we call it stack 

overflow

10 20 30 40 50 60 70 80 90 100

0 1 2 3 4 5 6 7 8 9

Top

Push(120) ===> Stack Overflow

POP operation

int Pop()

{

int elem = StackArray[top];top--; // Decrement the top pointer  

return elem;

}

10 20 30 40 50 60 70 80 90 100

0 1 2 3 4 5 6 7 8 9

Top

Pop()

Decrement the top pointer, Now Top = 9 so Top =9-1 =8

10 20 30 40 50 60 70 80 90 100

0 1 2 3 4 5 6 7 8 9

Top Now display the stack from index 0 to top position

for(int i=Top;i>=0;i--){ cout<<"\t"<<Array[i]<<"\n";}

 

Stack Underflow Condition

 Notes Compiled for M.S Software Engg A & B Batch - 5 -

8/8/2019 1186233570531_STACK

http://slidepdf.com/reader/full/1186233570531stack 6/26

Lecture Notes: 4

Once if the stack is empty and again data is deleted from the stack it is termed as

Stack Underflow condition. For example here stack is empty and top is pointing to -1

again if you try to delete data from the stack we call it stack underflow.

0 1 2 3 4 5 6 7 8 9

Top = -1 ===> Empty stack 

Pop() ===> Stack Underflow

STACK AS ADT

Abstract Data Type

• An Abstract Data Type is some sort of data together with a set

of functions (interface) that operate on the data.Access is only allowed through that interface.

Implementation details are ‘hidden’ from the user.

IMPLEMENTATION OF STACK ADT USING ARRAY

DS.H

#include<iostream.h>#include<conio.h>

#include<stdlib.h>

#define MaxSize 10

class Stack 

{

private:int Array[MaxSize];

int Top;

public:Stack()

{

Top = -1;}

void Push(int);int Pop();

void Display();};

 Notes Compiled for M.S Software Engg A & B Batch - 6 -

Abstract Data Type Stack 

8/8/2019 1186233570531_STACK

http://slidepdf.com/reader/full/1186233570531stack 7/26

Lecture Notes: 4

Implementation of ADT Stack 

void Stack::Push(int Data)

{

if(Top < MaxSize-1)Array[++Top] = Data;

else

{cout<<"\n\t Stack is full...";

getch();

}

}

int Stack::Pop()

{

if(Top>=0)return Array[Top--];

else{

return -1;

}

}

void Stack::Display()

{if(Top<0)

cout<<"\n\tStack Empty...";

else{

cout<<"\n\tElements in stack are : \n\n";

for(int i=Top;i>=0;i--){

cout<<"\t"<<Array[i]<<"\n";

}

}}

Stack as data type

Stack.cpp

#include "DS.h"

void main(){

Stack s;

int Choice,Data;

do { clrscr();

 Notes Compiled for M.S Software Engg A & B Batch - 7 -

8/8/2019 1186233570531_STACK

http://slidepdf.com/reader/full/1186233570531stack 8/26

Lecture Notes: 4

cout<<"Menu\n~~~~\n1.Push\n2.Pop\n3.Display\n4.Exit\n\tchoice: ";

cin>>Choice;

switch(Choice){

case 1:

cout<<"\nEnter the data to Push: ";cin>>Data;

s.Push(Data);

break;case 2:

int Res = s.Pop();

if(Res>=0)

cout<<"\n\t"<<Res<<" Popped out";else

cout<<"\n\tStack empty...";

getch();

break;case 3:

s.Display();getch();

break;

case 4:

cout<<"\n\tApplication closing.. \n\tPress any key to exit...";getch(); break;

default:

cout<<"\n\tError in choice...\n\tEnter correct choice..";getch();

break;

}}while(Choice!=4);

}

LINKED LIST IMPLEMENTATION OF STACK 

class LStack 

{ private:

struct Node

{int Data;

struct Node *Next;

}*Top; public:

LStack()

{

Top = NULL;

 Notes Compiled for M.S Software Engg A & B Batch - 8 -

8/8/2019 1186233570531_STACK

http://slidepdf.com/reader/full/1186233570531stack 9/26

Lecture Notes: 4

}

void Push(int Data)

{Node *NewNode = new Node;

NewNode->Data = Data;

NewNode->Next = NULL;if(Top == NULL)

{

Top = NewNode;}

else

{

NewNode->Next = Top;Top = NewNode;

}

}

int Pop(){

if(Top!=NULL){

Node * DelNode = Top;

int DelData = DelNode->Data;

Top = Top->Next;delete DelNode;

return DelData;

}else

{

return -1;}

}

void Display()

{

Node *CurrNode;

if(Top == NULL)cout<<"\n\n\tStack Empty...";

else

{cout<<"\n\n\tTop ==>> ["<<Top<<"]";

for(CurrNode = Top; CurrNode !=NULL;

CurrNode = CurrNode->Next)cout<<"\n\n<"<<CurrNode<<"> ["<<CurrNode->Data

<<" | "<<CurrNode->Next<<"]";

}

}};

 Notes Compiled for M.S Software Engg A & B Batch - 9 -

8/8/2019 1186233570531_STACK

http://slidepdf.com/reader/full/1186233570531stack 10/26

Lecture Notes: 4

APPLICATIONS OF STACK 

1. Balancing Symbols

2. Evaluation of arithmetic expressions• Evaluation of Postfix Expression.

• Evaluation of Prefix Expression.

3. Conversion of Infix to Postfix Expression.4. Conversion of Infix to Prefix Expression.

5. Recursive Algorithms

• Towers of Hanoi6. Reversing a String, Checking whether a string is Palindrome or not etc.

1. BALANCING SYMBOLS

Compilers make use of stack structures. This example shows a simple illustrationof the way a stack can be used to check the syntax of a program. It uses the Stack class

you have created.In the example, a Stack is used to check that the braces { and } used to mark out code

 blocks in a C++ source file are matched – i.e. that there are the same number of { as }.

• The source file is read character by character.

• Each time a { is read an object (any object, it doesn’t matter what) is pushed onto

the stack.

• Each time a } is read an object is popped from the stack.

• If the stack is empty when a } is read then there must be a missing { .

• If the stack is not empty at the end of the file then there must be a missing }

2. EVALUATION OF ARITHMETIC EXPRESSIONS

Algebraic Expressions, an Introduction:

An algebraic expression is a legal combination of operands and operators.

Operand is the quantity (unit of data) on which a mathematical operation is performed.

Operand may be a variable like x, y, z or a constant like 5, 4,0,9,1 etc. Operator is asymbol which signifies a mathematical or logical operation between the operands.

Example of familiar operators include +,-,*, /, ^ ('^' will be referred to as Exponential

Operator ) .Considering these definitions of operands and operators now we can write an

example of expression as x+y*z. Note the phrase "LEGAL combination" in the definitionof an Algebraic Expression, in aforementioned example of expression x+y*z, the

operands x , y, z and the operators +,* form some legal combination. Take another 

example +xyz*, in this expression operators and operands do not make any LEGALcombination; this expression is not a valid algebraic expression.

An Algebraic Expression can be represented using three different notations

• Infix

 Notes Compiled for M.S Software Engg A & B Batch - 10 -

8/8/2019 1186233570531_STACK

http://slidepdf.com/reader/full/1186233570531stack 11/26

Lecture Notes: 4

• Prefix (Polish Notation)

• Postfix (Reverse Polish Notation)

INFIX: From our school times we have been familiar with the expressions in which

operands surround the operator, e.g. x+y, 6*3 etc this way of writing the Expressions is

called infix notation. Operator is present in between the operands. Usually, arithmeticexpressions are written in infix notation.

e.g. A+B*C

PREFIX: Prefix notation also Known as Polish notation, is a symbolic logic invented by

Polish mathematician Jan Lukasiewicz in the 1920's. In the prefix notation, as the name

only suggests, operator comes before the operands, e.g. +xy, *+xyz etc.

e.g. +A*BC

POSTFIX: Postfix notation is also known as Reverse Polish notation (RPN). They are

different from the infix and prefix notations in the sense that in the postfix notation, the

operator comes after the operands, e.g. xy+, xyz+* etc.e.g. A+B*C

For example, will expression 3+5*4 evaluate to 32 i.e. (3+5)*4 or to 23 i.e.

3+(5*4). To solve this problem Precedence or Priority of the operators were defined.

Operator precedence governs evaluation order. An operator with higher precedence isapplied before an operator with lower precedence.

The following figure shows operator Precedence in descending order.

2.1. EVALUATING POSTFIX EXPRESSIONS

• Postfix expressions: operands precede operator 

• Example:

o z = 25 + x*(y – 5)

o Tokens: z, =, 25, +, x, *, (, y, -, 5, )

• Tokens: atomics of expressions, either operator or operand

 Notes Compiled for M.S Software Engg A & B Batch - 11 -

8/8/2019 1186233570531_STACK

http://slidepdf.com/reader/full/1186233570531stack 12/26

Lecture Notes: 4

EVALUATION ALGORITHM:

o Use stack of tokens

o Repeat

If operand, push onto stack 

If operator •  pop operands off the stack 

• evaluate operator on operands

•  push result onto stack 

Until expression is read

Return top of stack 

Explanation

Given an expression in postfix notation. Using a stack they can be evaluated as

follows:

o Scan the expression from left to right

o When a value (operand) is encountered, push it on the stack 

o When an operator is encountered, the first and second element from the

stack are popped and the operator is applied

The result is pushed on the stack 

Original expression: 1 + (2 + 3) * 4 + 5

Evaluate: 1 2 3 + 4 * + 5 +

PROCEDURE:

Input: 1 2 3 + 4 * + 5 + Input: 2 3 + 4 * + 5 +Push(1) Push(2)

 

1

 Notes Compiled for M.S Software Engg A & B Batch - 12 -

 

2

1

8/8/2019 1186233570531_STACK

http://slidepdf.com/reader/full/1186233570531stack 13/26

Lecture Notes: 4

Input: 3 + 4 * + 5 + Input: + 4 * + 5 +

Push(3) Pop() = = 3

Pop() = = 2

3

2

1

 

Input: + 4 * + 5 + Input: 4 * + 5 +

Push(2 + 3) Push(4)

Input: * + 5 + Input: * + 5 +

Pop() == 4 Push(5 * 4)Pop() == 5

 Notes Compiled for M.S Software Engg A & B Batch - 13 -

 

1

 

4

5

1

 

5

1

8/8/2019 1186233570531_STACK

http://slidepdf.com/reader/full/1186233570531stack 14/26

Lecture Notes: 4

 

1

Input: + 5 + Input: + 5 +Pop() == 20 Push(1 + 20)

Pop() == 1

 

Input: 5 + Input: +

Push(5) Pop() = = 21

Pop() = = 5

 

 Notes Compiled for M.S Software Engg A & B Batch - 14 -

 

20

1

 

21

 

8/8/2019 1186233570531_STACK

http://slidepdf.com/reader/full/1186233570531stack 15/26

Lecture Notes: 4

5

21

Input: + Input:

Push(21 + 5) Pop() == 26

 

26

Postfix Evaluation Implementation

Evaluate(postfix expression) {

// use stack of tokens;

while(// expression is not empty) {

t = next token;if (t is operand) {

// push onto stack 

} else {

// pop operands for t off stack // evaluate t on these operands

// push result onto stack 

}}

// return top of stack 

}

2.2. EVALUATING PREFIX EXPRESSIONS

Given an expression in prefix notation. Using a stack they can be evaluated as

follows:o Scan the expression from right to left.

o When a value (operand) is encountered, push it on the stack 

o When an operator is encountered, the first and second element from the

stack are popped and the operator is applied

o The result is pushed on the stack 

Original expression: (5+3) * (6-4)

 Notes Compiled for M.S Software Engg A & B Batch - 15 -

 

8/8/2019 1186233570531_STACK

http://slidepdf.com/reader/full/1186233570531stack 16/26

Lecture Notes: 4

Evaluate: *+53-64

PROCEDURE:

Input: *+53-64 Input: *+53-6

Push(4) Push(6)

 

4

Input: *+53- Input: *+53-

Pop() ==6 Push(6-4) = 2

Pop() == 4

 

 Notes Compiled for M.S Software Engg A & B Batch - 16 -

 

6

4

 

2

8/8/2019 1186233570531_STACK

http://slidepdf.com/reader/full/1186233570531stack 17/26

Lecture Notes: 4

Input: *+53 Input: *+5

Push(3) Push(5)

 

3

2

Input: *+ Input: *+

Pop() == 5 Push(5+3) = 8

Pop() == 3

 

2

Input: * Input: *Pop() == 8 Push(8*2)=16

Pop() == 2

 Notes Compiled for M.S Software Engg A & B Batch - 17 -

 

5

3

2

 

8

2

 

16

8/8/2019 1186233570531_STACK

http://slidepdf.com/reader/full/1186233570531stack 18/26

Lecture Notes: 4

Input:

Pop() == 16

3. CONVERSION OF INFIX TO POSTFIX EXPRESSION

Algorithm

Create an empty stack of operators.

While no error has occurred and the end of the infix expression has not been reached,do the following:

1. Get the next input Token (constant, variable, arithmetic operator, left and right parenthesis) in the infix expression.

2. If  Token is

(i) a left parenthesis:Push it onto the stack 

(ii) a right parenthesis:

Pop and display stack elements until a left parenthesis is

 popped, but do not display it. (It is an error if the stack becomesempty with no left parenthesis found.)

(iii) an operator:

If the stack is empty or Token has a higher priority than thetop stack, push Token onto the stack. Otherwise, pop and display

the top stack element, then repeat the comparison of Token with

the new top stack item.

 Notes Compiled for M.S Software Engg A & B Batch - 18 -

 

8/8/2019 1186233570531_STACK

http://slidepdf.com/reader/full/1186233570531stack 19/26

Lecture Notes: 4

A left parenthesis in the stack is assumed to have a lower 

 priority than that of operators.

(iv) an operand: Display it.

3. When the end of the infix expression is reached, pop and display stack items until

the stack is empty.

Example

(7+1)*(6+(3-2))

TOKEN Stack After Operation Display

( (

7 ( 7

+ (+ 7

1 (+ 7 1

) 7 1 +

* * 7 1 +( * ( 7 1 +

6 * ( 7 1 + 6

+ * ( + 7 1 + 6

( * ( + ( 7 1 + 6

3 * ( + ( 7 1 + 6 3

- * ( + ( - 7 1 + 6 3

2 * ( + ( - 7 1 + 6 3 2

) * ( + 7 1 + 6 3 2 -

) * 7 1 + 6 3 2 - +

• 7 1 + 6 3 2 - + displayed• Stack content *

• Add that to display

• 7 1 + 6 3 2 - + * Will be displayed as Postfix

Expression

4. CONVERSION OF INFIX TO PREFIX EXPRESSION

1) Reverse the input string.

2) Examine the next element in the input.

3) If it is operand, add it to output string.4) If it is closing parenthesis, push it on stack.

5) If it is an operator, then

i) If stack is empty, push operator on stack.ii) If the top of stack is closing parenthesis, push operator on stack.

iii) If it has same or higher priority than the top of stack, push operator on stack.

iv) Else pop the operator from the stack and add it to output string, repeat step 5.

6) If it is a opening parenthesis, pop operators from stack and add them to outputstring until a closing parenthesis is encountered. Pop and discard the closing

 parenthesis.

 Notes Compiled for M.S Software Engg A & B Batch - 19 -

8/8/2019 1186233570531_STACK

http://slidepdf.com/reader/full/1186233570531stack 20/26

Lecture Notes: 4

7) If there is more input go to step 2

8) If there is no more input, unstack the remaining operators and add them to

output string.9) Reverse the output string.

Example

Suppose we want to convert 2*3/(2-1)+5*(4-1) into Prefix form:

Reversed Expression: )1-4(*5+)1-2(/3*2

Char Scanned Stack Contents(Top on right) Prefix Expression(right to left)

) )

1 ) 1

- )- 1

4 )- 14

( Empty 14-

* * 14-

5 * 14-5

+ + 14-5*

) +) 14-5*

1 +) 14-5*1

- +)- 14-5*1

2 +)- 14-5*12

( + 14-5*12-

/ +/ 14-5*12-

3 +/ 14-5*12-3

* +/* 14-5*12-3

2 +/* 14-5*12-32

Empty 14-5*12-32*/+

Reverse the output string: +/*23-21*5-41

so, the final Prefix Expression is +/*23-21*5-41

 Notes Compiled for M.S Software Engg A & B Batch - 20 -

8/8/2019 1186233570531_STACK

http://slidepdf.com/reader/full/1186233570531stack 21/26

Lecture Notes: 4

5. RECURSIVE ALGORITHMS - TOWERS OF HANOI

A model set of the Towers of Hanoi

The Tower of Hanoi or Towers of Hanoi is a mathematical game or  puzzle. Itconsists of three pegs, and a number of discs of different sizes which can slide onto any

 peg. The puzzle starts with the discs neatly stacked in order of size on one peg, smallest

at the top, thus making a conical shape.

The objective of the game is to move the entire stack to another peg, obeying thefollowing rules:

• Only one disc may be moved at a time.

• Each move consists of taking the upper disc from one of the pegs and sliding it

onto another peg, on top of the other discs that may already be present on that peg.

•  No disc may be placed on top of a smaller disc.

Flag Tower of Hanoi

The puzzle was invented by the French mathematician Edouard Lucas in 1883.

There is a legend about an Indian temple which contains a large room with three time-worn posts in it surrounded by 64 golden discs. The priests of  Brahma, acting out the

 Notes Compiled for M.S Software Engg A & B Batch - 21 -

8/8/2019 1186233570531_STACK

http://slidepdf.com/reader/full/1186233570531stack 22/26

Lecture Notes: 4

command of an ancient prophecy, have been moving these discs, in accordance with the

rules of the puzzle. According to the legend, when the last move of the puzzle is

completed, the world will end. The puzzle is therefore also known as the Tower of Brahma puzzle. It is not clear whether Lucas invented this legend or was inspired by it.

If the legend were true, and if the priests were able to move discs at a rate of 1 per second, using the smallest number of moves, it would take them 2 64 − 1 seconds or 

roughly 586.549 billion years. The universe is currently about 13.7 billion years old.

There are many variations on this legend. For instance, in some tellings, the

temple is a monastery and the priests are monks. The temple or monastery may be said to

 be in different parts of the world - including Hanoi, Vietnam, and may be associated with

any religion. In some versions, other elements are introduced, such as the fact that thetower was created at the beginning of the world, or that the priests or monks may make

only one move per day.

The Flag Tower of Hanoi physically resembles an oversized version of the puzzlewith a single post and three stacked discs, and may have served as the inspiration for the

name.

Solving Towers of Hanoi problem with 3 discs

A B C

 1. Move disc 1from peg A to peg C

A B C

2. Move disc 2 from peg A to peg B

 Notes Compiled for M.S Software Engg A & B Batch - 22 -

1

1

8/8/2019 1186233570531_STACK

http://slidepdf.com/reader/full/1186233570531stack 23/26

Lecture Notes: 4

A B C

3. Move disc 1 from peg C to peg B and place it above disc2.

A B C

4. Move disc 3 from peg A to peg C

A B C

5. Move disc 1 from peg B to peg A

  A B C

6. Move disc 2 from peg B to peg C and place it above disc 3

 Notes Compiled for M.S Software Engg A & B Batch - 23 -

1

1

1

1

8/8/2019 1186233570531_STACK

http://slidepdf.com/reader/full/1186233570531stack 24/26

Lecture Notes: 4

  A B C

7. Move disc 1 from peg A to peg C and place it above disc 2

A B C

If there are n discs the number of moves will be 2n-1. Therefore for 3 discs

the number of moves is 23-1=7.

Solution

Most toy versions of the puzzle have 8 discs. The game seems impossible to many

novices, yet is solvable with a simple algorithm:

Recursive algorithm

• label the pegs A, B, C -- these labels may move at different steps

• let n be the total number of discs

• number the discs from 1 (smallest, topmost) to n (largest, bottommost)

To move n discs from peg A to peg B:

1. move n−1 discs from A to C. This leaves disc #n alone on peg A

2. move disc #n from A to B3. move n−1 discs from C to B so they sit on disc #n

The above is a recursive algorithm: to carry out steps 1 and 3, apply the samealgorithm again for n−1. The entire procedure is a finite number of steps, since at every

deeper level of recursion, n is decreased by one and hence at some point the algorithm

will be required for n = 1. The step of moving a single disc from peg A to peg B, istrivial.

 Notes Compiled for M.S Software Engg A & B Batch - 24 -

1

1

8/8/2019 1186233570531_STACK

http://slidepdf.com/reader/full/1186233570531stack 25/26

Lecture Notes: 4

The Tower of Hanoi is a problem often used to teach beginning programming, in

 particular as an example of a simple recursive algorithm. It is also an example of an

exponential time algorithm — for all but the smallest number of discs, it will take animpractically huge amount of time, even on the fastest computers in the world. There is

no way to improve on this, because the minimum number of moves required to solve the

 puzzle is exponential in the number of discs.

Using recurrence relations, we can compute the exact number of moves that thissolution requires, which is 2n − 1, where n is the number of discs. This result is obtained

 by noting that steps 1 and 3 take Tn − 1 time and step 2 takes constant time, giving Tn = 2Tn

− 1 + 1.

Explanation of the algorithm

A prose version of the same algorithm follows:

1. move disc 1 to peg B2. move disc 2 to peg C

3. move disc 1 from B to C, so it sits on 2

You now have 2 discs stacked correctly on peg C, peg B is empty again

1. move disc 3 to peg B

2. repeat the first 3 steps above to move 1 & 2 to sit on top of 3

Each time you re-build the tower from disc i up to 1, move disc i+1 from peg A, the

starting stack, and move the working tower again. Therefore, we can observe and say that

number of moves required to move n number of plates will be 2

n

− 1.

6. REVERSING A STRING

- Another e.g.: Reversing word order STACKS _ SKCATS

- Simply push each letter onto the stack, and then pop them.

The simplest application where we can exploit stack is when we have to put the

data in reverse order. Let’s assume that we have to change the characters in a character 

string in reverse order. One simple method to make it is as follows: First all charactersstarting from the beginning are pushed into a character stack. After that they are popped

out from the stack.

Let’s imagine, that you have to develop a program to check whether a string is

Palindrome or not. The word or sentence is a palindrome if you can spell it from the

 beginning to the end or from the end to the beginning and the result remains the same.

For example the Finnish word “saippuakauppias” (a merchant who sells soap) is probably

 Notes Compiled for M.S Software Engg A & B Batch - 25 -

8/8/2019 1186233570531_STACK

http://slidepdf.com/reader/full/1186233570531stack 26/26

Lecture Notes: 4

the most widely known palindrome in Finnish. Other examples are “Madam”,

“Malayalam”. When developing “the palindrome testing program” one solution is to use

three stacks as auxiliary components. First all characters are pushed onto the stack 1 andstack 2. After that all characters on at a time are popped from stack 2 and pushed onto

stack 3. The final step is that you pop characters from stack 1 and stack 3 parallel. If you

receive same characters all the time (up until the stacks are empty), the original string is palindrome.