First you need to decide what goes on the stack. This usually involves a complex structure.
Then you need to decide how you will store the stack. This i most often either an array or a dynamic linked list with a pointer for head and for tail. Stacks have a pointer to point to the item considered to be at the top of the stack.
Then you need to be careful of your terms. You said to insert or delete from the stack. If you mean "random insert" then this is not a stack, it is a queue. Ditto for random delete.
BUT if it is a single-ended queue with restrictions on random insert/delete such that you can only operate on the single "public" end selected by the stack pointer, then it is a stack. And in that case, you have two choices of operation. The PUSH is an insert to the top of the stack. The POP is a delete from the top of the stack.
Usually, if you are using arrays, you have an array of complex stack elements. The stack pointer is merely an index or array subscript for the stack structure or element that is currently considered "TOP of stack."
To push: Add one to the pointer that points to the top of the stack. Now store what you want in the newly selected top, which is technically empty until you store something. (Even if it really isn't empty, for stack terms it should be.)
To pop: You have a choice of discarding outright; or copying and then discarding. So if you are going to copy the top of the stack somewhere, do it. Then subtract one from the stack pointer.
The key is:
PUSH = change index and then STORE;
POP = COPY and then change index.
2007-12-06 16:36:51
·
answer #1
·
answered by The_Doc_Man 7
·
0⤊
0⤋