No
code here? Come on people! I can offer up my
Java implementation of a Stack, which is based on the Doubly
Linked List (which I have also
noded). This should help anyone struggling along (like I was) in a
Data Structures class. Even if you aren't using Java, the code is well
commented for easy
porting to other
languages. Note: this Stack takes
objects; not
primitive types. Enjoy!
//************************************************************
// This class defnines the Stack structure.
// It is based on a Linked List.
//************************************************************
public class MyStack extends ListClass
{
//************************************************************
// Declares an integer to hold the number of elements on the
// stack.
//************************************************************
private int numOnStack = 0;
//************************************************************
// This is the default constructor for the stack class.
// It assigns all omnipresent nodes to null.
//************************************************************
public MyStack()
{
start = current = end = null;
}
//************************************************************
// This method, push() takes an object and adds it to the
// stack. It also increments numOnStack.
//************************************************************
public void push(Object oneObject)
{
addBefore(oneObject);
numOnStack++;
}
//************************************************************
// This method, pop() removes the top element from the stack
// and returns the contents to the calling object. It also
// decrements numOnStack.
//************************************************************
public Object pop()
{
Object o = null;
current = start;
if(this.isEmpty() == false)
{
if(start.getNext() == null)
{
o = start.getObject();
current = start = end = null;
numOnStack--;
return(o);
}
else
{
o = start.getObject();
start = current = start.getNext();
numOnStack--;
return(o);
}
}
return("If you see this, there is an error.");
}
//************************************************************
// This method, getNumOnStack() returns the number of
// elements on the stack.
//************************************************************
public int getNumOnStack()
{
return numOnStack;
}
//************************************************************
// This method, isEmpty() determines if the stack is empty,
// using the int value of numOnStack as an indicator.
//************************************************************
public boolean isEmpty()
{
if(numOnStack == 0)
return true;
else
return false;
}
}