Skip to main content
Engineering LibreTexts

9.2: Stack Implementation

  • Page ID
  • There are two ways to implement a stack:

    • Using array
      • Pros: Easy to implement. Memory is saved as pointers are not involved.
      • Cons: It is not dynamic. It doesn’t grow and shrink depending on needs at runtime.
    • Using linked list
      • Pros: The linked list implementation of stack can grow and shrink according to the needs at runtime.
      • Cons: Requires extra memory due to involvement of pointers.

    We will look at using a Linked list to implement a Stack. Most of what we need to know we have already covered in our discussion of Linked Lists - stacks really only need a 'push' to build the stack. However, there are a couple of pieces that we need to add. In the "stack terminology" we have a 'pop' capability, which is just like the delete in our linked list. We also need to implement the 'peek' functionality - this simply returns the value that is sitting on the top of the stack, but does not alter the stack in any way. Lastly we will have to be able to determine if the stack is empty.

    We will look at some of the code pieces next.

    Adapted from: "Stack Data Structure (Introduction and Program)" by Bhupendra Rathore is licensed under CC BY-SA 4.0