I have a linked stack that I would like to copy over in to another stack so that it becomes in reverse order. How would I do that??
Basically this is how my stack is made.
struct Node
{
int num;
Node *Link;
};
MyStack::MyStack()
{
stackTop = new Node;
stackTop = NULL;
}
void MyStack::push(int num)
{
Node *newNode;
newNode = new Node;
assert(newNode != NULL);
newNode-%26gt;num = num;
newNode-%26gt;Link = stackTop;
stackTop = newNode;
}
Theres more to the code but this is all that matters for my question.
Thanks!
Copying a linked Stack in C++?
MyStack::MyStack()
{
// stackTop = new Node; // this "new Node" would be a memory leak
stackTop = NULL;
}
MyStack::( MyStack %26amp; o ) {
stackTop = NULL; // init my head
Node **ppNode = %26amp;stackTop; // point to pointer
Node * pNode = o.stackTop; // get other stack's head
while (pNode != NULL)
*ppNode = new Node; // make a new node
**ppNode = *pNode; // copy the other stack's node
(*ppNode)-%26gt;Link = NULL; // clear the new node's link
ppNode = %26amp;(*ppNode)-%26gt;Link; // point to the new node's link
pNode = pNode-%26gt;Link; // move to the other stack's next node
}
}
shoe decorations
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment