Skip to content

Instantly share code, notes, and snippets.

@dakerfp
Created January 25, 2022 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dakerfp/9ab3ee8931de20dfc3d9642d477c9ac3 to your computer and use it in GitHub Desktop.
Save dakerfp/9ab3ee8931de20dfc3d9642d477c9ac3 to your computer and use it in GitHub Desktop.
#include <stack>
#include <cassert>
using namespace std;
namespace hanoi {
static void move(stack<int>& from, stack<int>& to)
{
assert(!from.empty());
assert(to.empty() || to.top() > from.top());
to.push(from.top());
from.pop();
}
static void move_substack(stack<int>& from, stack<int>& to, stack<int>& temp, int depth)
{
if (depth <= 0)
return;
move_substack(from, temp, to, depth - 1);
move(from, to);
move_substack(temp, to, from, depth - 1);
}
static void move(stack<int>& from, stack<int>& to, stack<int>& temp)
{
move_substack(from, to, temp, from.size());
}
}
int main()
{
stack<int> from, to, temp;
for (int i = 5; i >= 1; i--)
from.push(i);
hanoi::move(from, to, temp);
assert(from.empty());
assert(temp.empty());
for (int i = 1; i <= 5; i++) {
assert(to.top() == i);
to.pop();
}
assert(to.empty());
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment