Advertisement
Guest User

Dynamic stack

a guest
Nov 20th, 2017
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.41 KB | None | 0 0
  1. public class DynamicStack {
  2.  
  3.     private class Node {
  4.  
  5.         Object element;
  6.         Node next;
  7.  
  8.         public Node(Object element, Node next) {
  9.             this.element = element;
  10.             next.next = this;
  11.         }
  12.  
  13.         Node(Object element) {
  14.             this.element = element;
  15.             this.next = null;
  16.         }
  17.  
  18.     }
  19.  
  20.     public Node head;
  21.     public Node tail;
  22.     public int count;
  23.  
  24.     public DynamicStack() {
  25.         this.head = null;
  26.         this.tail = null;
  27.         this.count = 0;
  28.     }
  29.  
  30.     public void push(Object o) {
  31.         if(head == null) {
  32.             head = new Node(o);
  33.             tail = head;
  34.         } else {
  35.             Node node = new Node(o, tail);
  36.             tail = node;
  37.         }
  38.         count++;
  39.     }
  40.  
  41.     public Object pop() {
  42.         Object popedElement = tail.element;
  43.  
  44.         count--;
  45.         if(count == 0) {
  46.             tail = null;
  47.             head = null;
  48.         } else {
  49.             int counter = 0;
  50.             DynamicStack.Node iterator = head;
  51.                 while (counter != count) {
  52.                     tail = iterator;
  53.                     iterator = iterator.next;
  54.                     counter++;
  55.                 }
  56.         }
  57.  
  58.         return popedElement;
  59.     }
  60.  
  61.     public Object peek() {
  62.         return this.tail.element;
  63.     }
  64.  
  65.     public int size() {
  66.         return this.count;
  67.     }
  68.    
  69.    
  70.  
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement