Reputation: 2818
I am starting to work with Stack in C++. I make the functions for push and pop. When we call the pop function it deletes the top data or info in the stack.
Is it possible to first find the data position in the stack and delete that position's data?
Upvotes: 2
Views: 876
Reputation: 5585
At first let me say that, you must listen to the fellows who are saying that stack is not the DS with which you need to play like this. A stack has been designed to follow a push and pop operation. If we try to delete any element from any position, then what's point of having a separate data structure exactly for such a purpose, you can use just an arraylist or a linked list.
Having said that, yes , what you ask can be done, but just because it can be, it should not be, otherwise, it defeats the whole purpose of having a DS like this. You can easily find the size of a stack, when you do that , you just need to iterate through it and delete a specific element from that position. But i would rather, you do not do that with stack .
Upvotes: 0
Reputation: 6678
If you're implementing the stack from scratch yourself, yes. How to do it depends on how it's implemented. If it's flat memory, you need to move the elements after the one you want to delete to the position of that element, thereby overwriting it. If it's a linked list, you need to make the element before the one you want to delete point to the one after it.
But it's an uncommon operation for a stack (a stack usually just supports pushing onto the end and popping from it). Maybe what you want is simply an array or linked list.
Upvotes: 0
Reputation: 34078
No, the whole point of a Stack is that it's FIFO, or first-in first-out. Whatever data you push onto the Stack is not accessible until data on top of that has been popped off of the Stack.
If you need to access data underneath the top layer, then you simply need to use another data structure, like an array or a list, for example.
I suggest you spend some time reading about C++ data structures. This will give you a better idea of what each data structure is used for, as well as when you should use a particular data structure. Good luck!
Upvotes: 4