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. { 
  17. Node oldfirst = first;
  18. first = new Node();
  19. first.item = item;
  20. first.next = oldfirst;
  21. N++;
  22. }
  23. public Item pop()
  24. { // Remove item from top of stack.
  25. Item item = first.item;
  26. first = first.next;
  27. N--;
  28. return item;
  29. }
  30. }



Comments

Popular posts from this blog

I get wrong characters when retreiving the message body of an email using TIdIMAP4.UIDRetrieveTextPeek2()

How to drop the all the 1's in a correlation matrix

Today Walkin 14th-Sept