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.
Stack
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

What is an interface?
Differences between ArrayList and LinkedList
Implement strtok() function. (It tokenizes the string )

Comments

One Response to “Implement a stack?”

  1. Tim on September 28th, 2008 12:21 am

    This is very nice post. Keep it up guys.

Leave a Reply




Technology