0
votes

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?

1
"So I have a stack with the typical Push and Pop functions that it allows" - sounds like you don't have that. Have you studied memory allocation as well as this particular data structure? Are you familiar with linked lists? - crashmstr
@crashmstr sorry, I mean I understand it without pointers. Working with pointers I have a hard time understanding it - SiggyxLeGiiT
Stacks add and remove from one end. So the "head" node changes on a push or pop. - crashmstr
@crashmstr Okay so I can add my new element at the end with the node* next, but I don't get how I can move backwards if I wanted to pop. There's no node previous, only a node next. - SiggyxLeGiiT
Don't add at the "back" end. A "push" adds a new node that then points to the old head of the stack (add/remove from the "front"). - crashmstr

1 Answers

0
votes

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;
}