// Final Node code for 9/10/2012 public class Node { // instance variables - replace the example below with your own public int data; public Node next; /** * Constructor for objects of class Node */ public Node() { data = 0; next = null; } public Node(int data) { this.data = data; next = null; } public Node(int data, Node next) { this.data = data; this.next = next; } public String toString() { String s = ""; return s + data + " "; } } /*************************************************************************************/ // Final stack code for 9/10/2012 public class Stack { // instance variables - replace the example below with your own private Node tos; /** * Constructor for objects of class Stack */ public Stack() { tos = null; } /** * An example of a method - replace this comment with your own * * @param y a sample parameter for a method * @return the sum of x and y */ public void push(int y) { Node n = new Node(y, null); if (tos == null) { tos = n; } else { n.next = tos; tos = n; } } public int pop() { if (isEmpty()) return -1; // horrible kludge until throwing exception! int data = tos.data; Node p = tos; tos = tos.next; return data; } public String toString() { String s = "<+"; Node p = tos; while (p != null) { // CANNOT use tos to step through stack! s += " "; s += p.data; p = p.next; } s += " ->"; return s; } public boolean isEmpty() { return tos == null; } public static void main (String[] args) { System.out.println("Start"); Stack s = new Stack(); s.push(5); s.push(3); s.push(17); s.push(1); System.out.println("stack: " + s); while(!s.isEmpty()) { System.out.println("popped: " + s.pop()); } System.out.println("stack: " + s); s.push(3); s.push(2); s.push(13); int x = s.pop(); System.out.println("final stack: " + s); System.out.println("Stop"); } } /*************************************************************************************/ // Output: Start stack: <+ 1 17 3 5 -> popped: 1 popped: 17 popped: 3 popped: 5 stack: <+ -> final stack: <+ 2 3 -> Stop