StackSLS.java (1513B)
1 package collections; 2 3 public class StackSLS<T> implements StackInterface<T> { 4 5 private Node<T> top; 6 // private int numItems; 7 8 public StackSLS() { 9 top = null; 10 } 11 12 public int size() { 13 int size = 0; 14 for (Node temp = top; temp != null; temp = temp.getNext()) { 15 size++; 16 } 17 return size; 18 } 19 20 public boolean isEmpty() { 21 return top == null; 22 } 23 24 public void popAll() { 25 top = null; 26 } 27 28 public void push (T item) { 29 top = new Node<T>(item, top); 30 } 31 32 public T pop() 33 throws StackException{ 34 T result; 35 if (top == null) { 36 throw new StackException("StackException: Stack is empty on pop"); 37 } 38 else { 39 result = top.getItem(); 40 top = top.getNext(); 41 return result; 42 } 43 } 44 45 public T peek() { 46 if (top == null) { 47 throw new StackException("StackException: Stack is empty on peek()"); 48 } 49 else { 50 return top.getItem(); 51 } 52 } 53 54 @Override 55 public String toString() { 56 Object dataItem; 57 Node curr = top; 58 String result = "Stack of size " + size() + " has the following items : "; 59 for (int i = 0; i < size(); i++) { 60 if (curr != null) { 61 dataItem = curr.getItem(); 62 curr = curr.getNext(); 63 result += dataItem + " "; 64 } 65 } 66 return result; 67 } 68 69 70 }