Thursday 10 October 2013

Stacked Link Lists

Here is my first attempt at working with simple, stacked link lists
//Copy Constructor
Stack::Stack(const Stack & S)
{
    _top = (Node *) 0;
    Node *newTemp;
    newTemp = S._top;
    Node *nex;
    nex = S._top;
    int count = 0;
    int newCount = 0;
    while (newTemp) {             //Count number of nodes
newTemp = newTemp->_next;
count++;
    }
    while (count) {
while (newCount < count - 1) {     //Move from first node to target node
   nex = nex->_next;
   newCount++;             //Nodes up to this point
}
count--;                             //reduce nodes counted
if (nex->_data) {
   push(nex->_data);             //Copy the respective node's content over to new Stack
}
nex = S._top;                     //Reset to first node
newCount = 0;                     //reset Nodes up to this point counter to zero
    }
}

//Method to reverse contents of a simple stack node
 void Stack::reverse()
{
    Node *nodeTemp;                            
    Node *newNode;
    int newCount = 0;
    if (this->_top)
newNode = this->_top;
    int count = 0;
    if (this->_top)
nodeTemp = this->_top;
    while (nodeTemp) {                             //Count number of nodes
nodeTemp = nodeTemp->_next;
count++;
    }
    while (count--) {
nodeTemp = this->_top;                              //reset to first Node
int temp = newNode->_data;                      //backup first node value
while (newCount++ < count) {
   nodeTemp = nodeTemp->_next;
}
if (newNode->_data == nodeTemp->_data)  //If nodes are equal at this point, means values have                                                                                      // been shifted fully
   count = 0;
else {
   newNode->_data = nodeTemp->_data; //copy over last node value
   nodeTemp->_data = temp;                         //copy over first node value
   newNode = newNode->_next;                 //Move to next node
}
newCount = 0;
    }
}


//Method to determine the number of nodes
unsigned int Stack::depth()
{
    int dept = 0;
    Node *new_top = this->_top;
    while (new_top) {
if (new_top->_data)
   new_top = new_top->_next;      //Jump to next node
dept++;                      //Increase counter value
    }
    return dept;
}

No comments:

Post a Comment