An object of type IntStack is a stack of real numbers, with the standard stack operations push(int N), pop(), and isEmpty(). A makeEmpty() operation is also provided to remove all items from the stack.

Internally, the stack is implemented as a linked list.

[code=’java’]
/*******************************************************
* MYCPLUS Sample Code – http://www.mycplus.com *
* *
* This code is made available as a service to our *
* visitors and is provided strictly for the *
* purpose of illustration. *
* *
* Please direct all inquiries to saqib at mycplus.com *
*******************************************************/

public class NumberStack {

private static class Node {
// An object of type Node holds one of the
// items on the stack;
double item;
Node next;
}

private Node top; // Pointer to the Node that is at the top of
// of the stack. If top == null, then the
// stack is empty.

public void push( double N ) {
// Add N to the top of the stack.
Node newTop = new Node();
newTop.item = N;
newTop.next = top;
top = newTop;
}

public double pop() {
// Remove the top item from the stack, and return it.
// Note that this routine will throw a NullPointerException
// if an attempty is made to pop an item from an empty
// stack. (It would be better style to define a new
// type of Exception to throw in this case.)
double topItem = top.item;
top = top.next;
return topItem;
}

public boolean isEmpty() {
// Returns true if the stack is empty. Returns false
// if there are one or more items on the stack.
return top == null;
}

} // end class NumberStack
[/code]

1 Shares
Share1
+1
Tweet
Share
Stumble