How to implement Linked List Using Stack?

Technology CommunityCategory: Linked ListsHow to implement Linked List Using Stack?
VietMX Staff asked 3 years ago

You can simulate a linked list by using two stacks. One stack is the “list,” and the other is used for temporary storage.

  • To add an item at the head, simply push the item onto the stack.
  • To remove from the head, pop from the stack.
  • To insert into the middle somewhere, pop items from the “list” stack and push them onto the temporary stack until you get to your insertion point. Push the new item onto the “list” stack, then pop from the temporary stack and push back onto the “list” stack. Deletion of an arbitrary node is similar.

This isn’t terribly efficient, by the way, but it would in fact work.