Is there a more efficient implementation than using stacks?