/*Isaac Sarver
Started 9/16/10
Converted to char on 9/19/10.
This is the class for a stack of Type. It will be doublely linked.*/
#include
using namespace std;
#include"./Stack.h"
void Stack::Push(Type x) //Add Node to Tail
{
nodeptr n = new node; //General node pointer
n->value = x; //Store new value in n
n->prev = NULL; //Point previous to NULL, there may not be a previous node if empty list
n->next = NULL; //Point next to NULL
count++; //Increament size
if(head == NULL) //If empty list
{
head = n; //Point head and tail to n
tail = n;
}
else
{
n->prev = tail; //point prev at present tail
tail->next = n; //point next of prev node, which is tail, to n
tail = n; //point tail at new head node
} //Increamenting indices is not needed as this is going at the tail
return;
}
Type Stack::Pop() //pop
{
nodeptr n = tail; //General n point and point it at the node to go away
Type deleted;
if(n != NULL) //If the stack isn't already empty
{
deleted = tail->value; //Value to be returned
count--; //Decreament the counter
if(tail->prev != NULL) //I think this line will cause a Seg Fault if list of 1
{
tail = tail->prev; //Advance tail
}
tail->next = NULL; //Point the new tail's next into the void
n->prev = NULL; //Disconnect n from list
delete n; //Delete n
}//Decreamenting indices is not needed as it was the last one that went away
if(count == 0) //To return the list to the orginal state to accept new nodes without ill effect
{
head = NULL;
tail = NULL;
}
return(deleted);
}
Type Stack::Peek()
{
return(tail->value);
}
int Stack::Size() //Returns the length of the list
{
return(count);
}
void Stack::Print()
{
nodeptr n = head; //General node pointer and start at the head
int i, j;
while(n != NULL) //While n has not fallen off the end of the stack
{
cout << n->value << endl; //outputs extra line between each node
n = n->next; //Advance n
}
return;
}
bool Stack::operator==(Stack & other)
{
bool truth = true; //Assume true
nodeptr n = head;
nodeptr m = other.head;
if(count == other.count) //If both are same length
{
if(count == 0) //If size is zero
{
if(head != other.head) //check to see if both heads are pointing at same place, only happening if NULL
{
truth = false;
}
else if(tail != other.tail) //check to see if both tails are point at same place, only happening if NULL
{
truth = false;
}
}
else //If non-zero size
{
while(n != NULL) //While the pointer hasn't fallen off of the cliff
{
if(n->value != m->value) //If current position is not equal
{
truth = false;
break; //break
}
n = n->next; //Advance pointers
m = m->next;
}
}
}
else //Not same size
{
truth = false;
}
return(truth);
}
void Stack::operator=(Stack other)
{
nodeptr m = other.head;
while(count != 0) //Clear out (*this) stack
{
Pop();
}
while(m != NULL) //Stores other stack to (*this) stack
{
Push(m->value);
m = m->next;
}
return;
}