From b9b930213fc2a2e7c86b335cc70099c45a6c24ea Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 16:05:43 -0400 Subject: [PATCH] use pointers instead of non-const references and globals --- others/tower_of_hanoi.cpp | 37 ++++++++++++++++++++----------------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/others/tower_of_hanoi.cpp b/others/tower_of_hanoi.cpp index d6c229617..323b2e424 100644 --- a/others/tower_of_hanoi.cpp +++ b/others/tower_of_hanoi.cpp @@ -13,21 +13,22 @@ struct tower { int values[10]; //! top tower ID int top; -} F, U, T; +}; /** Display the towers */ -void show() { +void show(const struct tower *const F, const struct tower *const T, + const struct tower *const U) { std::cout << "\n\n\tF : "; - for (int i = 0; i < F.top; i++) { - std::cout << F.values[i] << "\t"; + for (int i = 0; i < F->top; i++) { + std::cout << F->values[i] << "\t"; } std::cout << "\n\tU : "; - for (int i = 0; i < U.top; i++) { - std::cout << U.values[i] << "\t"; + for (int i = 0; i < U->top; i++) { + std::cout << U->values[i] << "\t"; } std::cout << "\n\tT : "; - for (int i = 0; i < T.top; i++) { - std::cout << T.values[i] << "\t"; + for (int i = 0; i < T->top; i++) { + std::cout << T->values[i] << "\t"; } } @@ -35,10 +36,10 @@ void show() { * \param [in,out] From tower to move disk *from* * \param [in,out] To tower to move disk *to* */ -void mov(tower &From, tower &To) { - --From.top; - To.values[To.top] = From.values[From.top]; - ++To.top; +void mov(tower *From, tower *To) { + --From->top; + To->values[To->top] = From->values[From->top]; + ++To->top; } /** @@ -48,20 +49,22 @@ void mov(tower &From, tower &To) { * \param [in,out] Using temporary tower for the puzzle * \param [in,out] To tower to move disk to */ -void TH(int n, tower &From, tower &Using, tower &To) { +void TH(int n, tower *From, tower *Using, tower *To) { if (n == 1) { mov(From, To); - show(); + show(From, To, Using); } else { TH(n - 1, From, To, Using); mov(From, To); - show(); + show(From, To, Using); TH(n - 1, Using, From, To); } } /** Main function */ int main() { + struct tower F, U, T; + F.top = 0; U.top = 0; T.top = 0; @@ -75,8 +78,8 @@ int main() { F.values[F.top++] = i; } - show(); - TH(no, F, U, T); + show(&F, &T, &U); + TH(no, &F, &U, &T); return 0; }