/* File: StackLL.java * Author: Wayne Snyder (waysnyder@gmail.com) * Data: Jul 29, 2020 * Purpose: Example of Deque implemented by Doubly-Linked List */ import java.util.Arrays; public class StackLL { private class Node { int item; Node next; public Node(int i, Node n) { item = i; next = n; } } private Node top = null; private int size = 0; // put a new int on top of the stack public void push(int i) { top = new Node(i,top); ++size; } // remove top int from the stack and return it public int pop() { int n = top.item; top = top.next; --size; return n; } // return top int without removing it public int top() { return top.item; } // number of ints in the stack public int size() { return size; } // is the stack empty? public boolean isEmpty() { return size == 0; } // just for debugging and tracing public String toString() { String s = "top-> "; for(Node p=top; p!=null; p=p.next) { s += p.item + " -> "; } return s + "."; } public static void main(String[] args) { System.out.println("\nUnit Test for Stack ADT"); StackLL SLL = new StackLL(); // test size and isEmpty on empty stack System.out.println("\nsize() => " + SLL.size()); System.out.println("\nisEmpty() => " + SLL.isEmpty()); System.out.println("\nPush 3, 6 and 7: "); SLL.push(3); SLL.push(6); SLL.push(7); System.out.println(); System.out.println(SLL); System.out.println("\nsize() => " + SLL.size()); System.out.println("\nisEmpty() => " + SLL.isEmpty()); System.out.println("\npop() => " + SLL.pop()); System.out.println("\npop() => " + SLL.pop()); System.out.println("\nPush 7:"); SLL.push(7); System.out.println(); System.out.println(SLL); System.out.println("\nsize() => " + SLL.size()); System.out.println("\nisEmpty() => " + SLL.isEmpty()); // Now test resizing for(int i = 9; i<100; i += 2) { SLL.push(i); } System.out.println(); System.out.println(SLL); while(!SLL.isEmpty()) { SLL.pop(); } System.out.println(); System.out.println(SLL); System.out.println("\nsize() => " + SLL.size()); System.out.println("\nisEmpty() => " + SLL.isEmpty()); } }