package DataStructures;
publicclass LinkedStack
{ private ListNode topOfStack; public LinkedStack() { topOfStack = null; } publicboolean IsFull() { returnfalse; } publicboolean IsEmpty() { return topOfStack == null; } publicvoid makeEmpty() { topOfStack = null; } /** * Insert a new item into the stack. * * @param x * the item to insert. */ publicvoid 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()) returnnull; return topOfStack.element; } /** * Remove the most recenly inserted item from the stack. * * @throws Underflow */ publicvoid Pop() throws Underflow { if (IsEmpty()) thrownew 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()) returnnull; 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. */ publicclass Underflow
extends Exception
{ }