Implement a stack?
A stack is an ordered list in which all insertions and deletions are made at one end, called the top. We can picture a stack as in the following figure.

The last element inserted is the first element deleted. Thus E is deleted before D because E was inserted after D. For this reason a stack is sometime called last-in, first-out (LIFO). Implementation of stack in Java
public class MyStack extends Vector {
/**
* Constructor creates an empty stack
*/
public MyStack() {
}
/**
* Pushes an Object onto the top of the stack
*/
public Object push(Object item) {
addElement(item);
return item;
}
/**
* Pops an item from the stack and returns it. The item popped is
* removed from the Stack.
*/
public Object pop() {
if (isEmpty()) {
throw new EmptyStackException();
}
Object item = elementData[--elementCount];
// Release memory used by this element
elementData[elementCount] = null;
return item;
}
/**
* Returns the top Object on the stack without removing it.
*/
public Object peek() {
if (isEmpty()) {
throw new EmptyStackException();
}
return elementData[elementCount - 1];
}
/**
* Check if the stack is empty.
*/
public boolean isEmpty() {
return elementCount == 0;
}
}
Related Post
Comments
One Response to “Implement a stack?”
Leave a Reply
This is very nice post. Keep it up guys.