Reputation: 409
If I were to remove an element from a stack, what runtime error could occur, and how could I prevent the program from terminating abnormally? Also can you give me an example? I am having a hard time understanding this concept in my book here.
Upvotes: 0
Views: 182
Reputation: 68
I am having a hard time understanding this concept in my book here.
I always thought of the Stack data structure as a stack of lunch trays. To add a new tray to the stack, you have to place it on top of the other trays (push). Whenever you need to remove a tray, you are only able to remove the top tray in the stack (pop).
If I were to remove an element from a stack, what runtime error could occur, and how could I prevent the program from terminating abnormally?
When removing an element from a stack, you are only able to take off the most recent element put into. This is called LIFO order (Last In First Out). To prevent any problems from occurring, you'll always need to make sure the stack is not empty when attempting to remove an item.
Upvotes: 1