Stack(LIFO) implementation in java (linkedlist)


A stack is a collection that is based on the last-in-first-out (LIFO) policy.
  • push() -  push an item into stack.
  • pop() - get an item and remove it from the top.



(This Stack implementation is based on a linked-list data structure)

  1. public class Stack<Item> implements Iterable<Item>
  2. {
  3.  // top of stack (most recently added node)
  4. private Node first;
  5.  // number of items
  6. private int N;
  7. private class Node
  8. {
  9. Item item;
  10. Node next;
  11. }
  12. public boolean isEmpty() { return first == null; } // Or: N == 0.
  13. public int size() { return N; }
  14. // Add item to top of stack.
  15. public void push(Item item)
  16. Node oldfirst = first;
  17. first = new Node();
  18. first.item = item;
  19. first.next = oldfirst;
  20. N++;
  21. }
  22. public Item pop()
  23. { // Remove item from top of stack.
  24. Item item = first.item;
  25. first = first.next;
  26. N--;
  27. return item;
  28. }
  29. }



Comments

Popular posts from this blog

Today Walkin 14th-Sept

Hibernate Search - Elasticsearch with JSON manipulation

Spring Elasticsearch Operations