So I have a stack with the typical Push and Pop functions that it allows. I'm having a hard time wrapping my head around how it all actually works code-wise. I saw this post here,
Picture/Diagram in the best answer that shows how the list is "pushed" down and you point at the newest element. I have a
node* stack;
which is hooked to a struct "node"
struct node
{
ItemType data;
node* next;
};
How do I incorporate a push and pull with a "node* next;" ? The hard part to wrap my head around is how I'm going to actually do it. I know it initially points at null, and then if I were to push a 2,4,6 it would be 6,4,2,#. Grasping how to actually do it with pointers in a linked list throws me for a loop. I can do it without pointers but the pointers are what get me. Thank you for any help, I really wanna work through this. I'm here to comment back too quickly. Thanks!
EDIT 1:
solved - my push is working
EDIT 2:
I'm trying to pop now. Would that mean I have to just aim my pointer at the next value? What do I do to the old top node? delete it since I new'd it?
Answer
It looks like a C question.
Functions push can be defined in C++ the following way
void push( node * &stack, const ItemType &item )
{
node *tmp = new node { item. stack };
stack = tmp;
}
in C it can look like
int push( struct node * *stack, const ItemType *item )
{
node *tmp = malloc( sizeof( struct node ) );
if ( tmp )
{
tmp->data = *item;
tmp->next = *stack;
*stack = tmp;
}
return tmp != NULL;
}
EDIT: After you edited your post I also edited my post.
It seems that pointer stack is a data member of class StackClass. In this case the member function can look like
void StackClass::Push( ItemType newItem )
// I would declare the parameter as const ItemType &newItem
{
node* temp = new node;
temp->data = newItem;
temp->next = stack;
stack = temp;
}
No comments:
Post a Comment