Wrox Home  
Search P2P Archive for: Go

  Return to Index  

pro_java thread: TestStackPT.java


Message #1 by "Sam" <sam-armen@e...> on Fri, 12 Apr 2002 05:00:38 -0400 (EDT)


--EXCITEBOUNDARY_000__b97580c8ce0ef706c8a2571436cdc1c5
Content-Type: text/plain; charset="us-ascii"
Content-Transfer-Encoding: 7bit

 How do I change TestStackPT.java to test both the array and linked implementation in one executiion of the program?









import BreezyGUI.*; 



public class TestStackPT{ 

public static void main (String[] args){ 

StackPT s = new ArrayStackPT(10); 

//StackPT s = new LinkedStackPT(); 



try{ 

String str = (String)s.peek(); 

}catch (Exception e){ 

System.out.println("Expect error because peeking when empty:\n" + e); 

} 



for (int i = 0; i  0"); 

stack = new Object[capacity]; 

top = -1; 

} 



public boolean isEmpty(){ 

return top == -1; 

} 



public boolean isFull(){ 

return size() == stack.length; 

} 



public Object peek(){ 

if (isEmpty()) 

throw new IllegalStateException ("Stack is empty"); 

return stack[top]; 

} 



public Object pop(){ 

if (isEmpty()) 

throw new IllegalStateException ("Stack is empty"); 

Object topItem = stack[top]; 

stack[top] = null; 

top--; 

return topItem; 

} 



public void push(Object item){ 

if (item == null) 

throw new IllegalArgumentException ("Item is null"); 

if (isFull()) 

throw new IllegalStateException ("Stack is full"); 

top++; 

stack[top] = item; 

} 



public int size(){ 

return top + 1; 

} 

} 











import java.io.Serializable; 



public class LinkedStackPT implements StackPT, Serializable { 



private int count; // Number of items in the stack 

private Node top; // Top node in the stack 



public LinkedStackPT(){ 

top = null; 

count = 0; 

} 



public boolean isEmpty(){ 

return count == 0; 

} 



public boolean isFull(){ 

return false; 

} 



public Object peek(){ 

if (isEmpty()) 

throw new IllegalStateException ("Stack is empty"); 

return top.value; 

} 



public Object pop(){ 

if (isEmpty()) 

throw new IllegalStateException ("Stack is empty"); 

count--; 

Object item = top.value; 

top = top.next; 

return item; 

} 



public void push(Object item){ 

if (item == null) 

throw new IllegalArgumentException ("Item is null"); 

count++; 

Node n = new Node (item, top); 

top = n; 

} 



public int size(){ 

return count; 

} 



private class Node implements Serializable { 



private Object value; // Value stored in this node 

private Node next; // Reference to next node 



private Node(){ 

value = null; 

next = null; 

} 



private Node(Object value, Node next){ 

this.value = value; 

this.next =next; 

} 

} 

}








------------------------------------------------




  Return to Index