This project implements the classic Tower of Hanoi puzzle in the C programming language. The goal is to complete the stack data structure and its core operations (peek, pop, moveDisk, push, isEmpty). The remaining logic for displaying the stacks and handling input is already provided.
- Introduction
- Data Structures
- Stack Operations
- Game Control Functions
- How to Compile and Run
- How to Play
- License
The Tower of Hanoi is a mathematical puzzle where the objective is to move a stack of disks from one tower to another, following specific rules:
- Only one disk can be moved at a time.
- Each move consists of taking the top disk from one of the stacks and placing it on top of another stack.
- No disk may be placed on top of a smaller disk.
Each node in the singly linked list represents a disk.
typedef struct Node {
int disk; // The disk's size (larger number means larger disk)
struct Node *next; // Pointer to the next node
} Node;Each tower is represented as a stack.
typedef struct {
Node *top; // Pointer to the top node of the stack
} Stack;void initStack(Stack *s);bool isEmpty(Stack *s);void push(Stack *s, int disk);int pop(Stack *s);int peek(Stack *s);
void printAllTowers(Stack *A, Stack *B, Stack *C);void printTower(Stack *tower, char name);bool isValidMove(Stack *from, Stack *to);bool moveDisk(Stack *from, Stack *to, char fromName, char toName);bool areAllDisksInOneTower(Stack *X, int n);void initializeGame(Stack *A, Stack *B, Stack *C, int n);
-
Open a terminal and navigate to the project directory.
-
Compile the code using
gcc:gcc hanoi_towers_game.c -o hanoi_towers_game
-
Run the executable:
./hanoi_towers_game
- Enter the number of disks when prompted.
- The game will display the initial state of the towers.
- Enter your moves in the format
A Bto move the top disk from Tower A to Tower B. - The game continues until all disks are in one tower or you choose to quit by entering
Q.