Stack Push() and Pop() Methods in Java

Jonathan Rasmusson
A free video tutorial from Jonathan Rasmusson
Ex-Spotify Engineer, The Agile Samurai
4.4 instructor rating • 5 courses • 41,631 students

Learn more from the full course

Data Structures and Algorithms Bootcamp

How to ace your Silicon Valley style coding interview

06:27:06 of on-demand video • Updated October 2020

  • How to answer commonly asked Silicon Valley style interview questions
  • Demonstrate knowledge and mastery of data structures and algorithms
  • How to pass Silicon Valley style technical interviews
  • Interview confidently
  • Land your dream job
English Pushing onto a stack is basically the exact same operation as adding front into a linked list. We just create a new node containing the data we want to push onto the top of our stack. We then point that new nodes next to our head and then reset the head to point to the new node that we just created. This effectively merges the newly created element into the top of our stack and now we have a fully combined, ready to go, linked list. Again this is an O(1) operation. Very quick very fast. One of the killer features of pushing onto a stack. And in code it looks like this. We simply have our API which takes a piece of data we'd like to store. We create the new node. We set the new nodes next equal to the head. And then we just re-point the head to the new node that we just created. That's effectively push. Popping off of the stack. Very similar. Here we just first store the data we'd like to return when we pop off a stack and then we simply take the head and point it to the next node in our linked list, bypassing the very top one. that effectively removes the top node. We have the data that we want to return and then we simply return it. Again that's an O(1) operation. Very very fast. And in code popping off a stack looks just like this. First we can do a check to see if the head is equal to null, then know and if it is through an empty stack exception. But basically it's just this store the data we want to return take the head and bypass its self currently and point to the next element and then simply return the data. That's how we pop something off of the stack.