package edu.columbia.cs.cs1007.datastructures;
import java.util.LinkedList;
/**
* An implementation of the stack data structure
* using Java's built-in LinkedList
*
* @author Julia Stoyanovich, jds2109@columbia.edu
* COMS 1007, Summer 2009
*
*/
public class MyStack {
LinkedList<Integer> _stack;
/**
* Constructor.
*/
public MyStack() {
_stack = new LinkedList<Integer>();
}
/**
* Constructor. What is the problem with this constructor
* if we were to use a singly-linked list?
* @param inArr
*/
public MyStack(int[] inArr) {
this();
for (int num : inArr) {
// adds an element to the tail of the list
_stack.addLast(num);
}
}
/**
* For singly-linked lists, add to the front,
* not to the end, much more efficient!
* @param inArr
* @param fast
*/
public MyStack(int[] inArr, boolean fast) {
this();
for (int i=inArr.length-1; i>=0; i--) {
_stack.add(inArr[i]);
}
}
/**
* Check whether there are any entries in the list
* @return true if list is empty, false otherwise
*/
public boolean isEmpty() {
return (_stack.isEmpty());
}
/**
* Push an element onto the stack.
* @param num
*/
public void push(int num) {
// adds an element to the head of the list
_stack.addFirst(num);
}
/**
* Pop an element from the head of the stack.
* @return
*/
public int pop() {
// removes first element in the list
return _stack.removeFirst();
}
/**
* Generate a string representation of the stack.
* @return string representation
*/
public String toString() {
StringBuffer res = new StringBuffer();
while (!_stack.isEmpty()) {
res.append(" " + _stack.pop());
}
return res.toString();
}
}
|