Assign values of a stack to another stack

跟風遠走 提交于 2019-12-12 03:18:25

问题


I am working on this assignment.

I need to create a temporary stack without initializing it.

Then push the items of stack 1 into this temporary stack using a while loop.

Then I need to use another (nested?) loop to walk through the temp stack and add the items from temp stack onto stack 2.

Then I need to set stack 1 and 2 equal so stack 2 remains unchanged.


回答1:


Your interfaces look a bit off. Let's start there and see if that gets you over your hump.

stack.top() usually peeks at an item, but doesn't remove it. This doesn't seem useful for transfering from one stack to anther. You already have isEmptyStack() to check that the top element exists.

stack.pop() usually takes the top item from a stack. This sounds useful for transferring.

stack.push(item) places item onto the top of the stack. This sounds useful for transferring.

stack.push() just seems wrong. Push what?

Hopefully, once you implement these methods, the rest will start to make sense from the english description of the problem you provided.

Update: this is what you want:

|a  |   |     |   |   |     |   |   |     |   |c  |
|b  |   |     |b  |   |     |   |b  |     |   |b  |
|c  |   |     |c  |a  |     |c  |a  |     |   |a  |
1   tmp 2     1   tmp 2     1   tmp 2     1   tmp 2

|   |   |     |   |   |     |   |   |a
|   |b  |     |   |   |b    |   |   |b
|   |a  |c    |   |a  |c    |   |   |c
1   tmp 2     1   tmp 2     1   tmp 2 

Now, with just push, pop, and IsEmptyStack, with no assigning of stacks to one another (that sort of defeats the purpose of the assignment), can you do this?



来源:https://stackoverflow.com/questions/8948795/assign-values-of-a-stack-to-another-stack

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