Towers of Hanoi using Stack
Tower of Hanoi is a mathematical puzzle where we have three rods (A, B, and C) and N disks. Initially, all the disks are stacked in decreasing value of diameter i.e., the smallest disk is placed on the top and they are on rod A. The objective of the puzzle is to move the entire stack to another rod (here considered C), obeying the following simple rules:
- Only one disk can be moved at a time.
- Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
- No disk may be placed on top of a smaller disk.
Examples:
Input: 3
Output: Disk 1 moved from A to C
Disk 2 moved from A to B
Disk 1 moved from C to B
Disk 3 moved from A to C
Disk 1 moved from B to A
Disk 2 moved from B to C
Disk 1 moved from A to C
Tower of Hanoi using Recursion:
The idea is to use the helper node to reach the destination using recursion. Below is the pattern for this problem:
- Shift ‘N-1’ disks from ‘A’ to ‘B’, using C.
- Shift last disk from ‘A’ to ‘C’.
- Shift ‘N-1’ disks from ‘B’ to ‘C’, using A.
Follow the steps below to solve the problem:
- Create a function towerOfHanoi where pass the N (current number of disk), from_rod, to_rod, aux_rod.
- Make a function call for N – 1 th disk.
- Then print the current the disk along with from_rod and to_rod
- Again make a function call for N – 1 th disk.
Time complexity: O(2N), There are two possibilities for every disk. Therefore, 2 * 2 * 2 * . . . * 2(N times) is 2N
Auxiliary Space: O(N), Function call stack space
Stack Notes for GATE Exam [2024]
Stacks, a fundamental data structure in computer science, are crucial for understanding algorithmic paradigms and solving complex computational problems. As candidates gear up for the GATE Exam 2024, a solid grasp of stack concepts is indispensable. These notes are designed to provide a concise yet comprehensive overview of stacks, covering key topics that are likely to be assessed in the GATE examination.
Table of Content
- Introduction to Stack:
- LIFO (Last In First Out) in Stack:
- Basic Operations on Stack
- Implementation of Stack using Singly Linked List:
- Applications, Advantages and Disadvantages of Stack:
- Infix to Postfix Operation in Stack:
- Postfix Evaluation using Stack:
- Towers of Hanoi using Stack:
- Fibonaaci Series using Stack:
- Previously Asked GATE Questions on Stack: