Design a stack that can also dequeue in O(1) amortized time?

微笑、不失礼 提交于 2019-12-05 13:22:51

Making a few assumptions:

  1. That this is homework
  2. That this paragraph is part of the assignment

Implement this using three stacks and constant additional memory, so that the amortized time for any push, pop, or pull operation is constant. The stacks have basic operations, isEmpty, Push, and Pop.

Then my first advice would be to ignore the people talking to you about linked lists. True, that's how any reasonable person would implement it without the three stack requirement, but the key factor in homework isn't to do it the way a reasonable person would, but rather how your instructor wants you to.

My second bit of advice would be to get some blocks, a deck of cards, or a bunch of styrofoam cups and designate three stacks (e.g. with coasters or something). Start playing around with what happens when you transfer the contents of one stack to another, and that should give you an idea.

You could do something which uses only the 3 stacks. Think tower of Hanoi.

Use a doubly-linked list and keep pointers to the head and tail. For the rest, you need to write your own code first and then let us help you correct it.

Start by implementing a queue in terms of two stacks (a pretty standard problem) and generalize.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!