主类
package DataStructures;
public class LinkedStack {
private ListNode topOfStack;
public LinkedStack() {
topOfStack = null;
}
public boolean IsFull() {
return false;
}
public boolean IsEmpty() {
return topOfStack == null;
}
public void makeEmpty() {
topOfStack = null;
}
/**
* Insert a new item into the stack.
*
* @param x
* the item to insert.
*/
public void Push(Object x) {
topOfStack = new ListNode(x, topOfStack);
}
/**
* Get the most recently inserted item in the stack. Does not alter the
* stack
*
* @return the most recently inserted item in the stack, or null if empty
*/
public Object Top() {
if (IsEmpty())
return null;
return topOfStack.element;
}
/**
* Remove the most recenly inserted item from the stack.
*
* @throws Underflow
*/
public void Pop() throws Underflow {
if (IsEmpty())
throw new Underflow();
topOfStack = topOfStack.next;
}
/**
* Return and remove the most recently inserted item from the stack.
*
* @return the most recently iserted item in the stack, or null if empty.
*/
public Object TopAndPop() {
if (IsEmpty())
return null;
Object topItem = topOfStack.element;
topOfStack = topOfStack.next;
return topItem;
}
}
public class LinkedStack {
private ListNode topOfStack;
public LinkedStack() {
topOfStack = null;
}
public boolean IsFull() {
return false;
}
public boolean IsEmpty() {
return topOfStack == null;
}
public void makeEmpty() {
topOfStack = null;
}
/**
* Insert a new item into the stack.
*
* @param x
* the item to insert.
*/
public void Push(Object x) {
topOfStack = new ListNode(x, topOfStack);
}
/**
* Get the most recently inserted item in the stack. Does not alter the
* stack
*
* @return the most recently inserted item in the stack, or null if empty
*/
public Object Top() {
if (IsEmpty())
return null;
return topOfStack.element;
}
/**
* Remove the most recenly inserted item from the stack.
*
* @throws Underflow
*/
public void Pop() throws Underflow {
if (IsEmpty())
throw new Underflow();
topOfStack = topOfStack.next;
}
/**
* Return and remove the most recently inserted item from the stack.
*
* @return the most recently iserted item in the stack, or null if empty.
*/
public Object TopAndPop() {
if (IsEmpty())
return null;
Object topItem = topOfStack.element;
topOfStack = topOfStack.next;
return topItem;
}
}
异常类
package DataStructures;
/**
* Exception class for access in empty containers such as stacks, queues, and
* priority queues.
*/
public class Underflow extends Exception {
}
/**
* Exception class for access in empty containers such as stacks, queues, and
* priority queues.
*/
public class Underflow extends Exception {
}