views:

306

answers:

1

Does anybody know where I can find an example of a Spaghetti stack written in C?

+3  A: 

It should be something similar to that:

struct stack_item;

struct stack_item
{
    stack_item *parent;
    void *ptr_data;
};

stack_item *stack_pointer = null;

void push(stack_item *item)
{
    if (stack_pointer == null)
     item->parent = null;
    else
     item->parent = cur; 

stack_pointer = item;
}

/* like push but doesn't update cur stack item to the one pushed, just add a child */
void push_parallel(stack_item *item)
{
    if (stack_pointer == null)
    {
     stack_pointer = item;
     item->parent = null;
    }
    else
     item->parent = stack_pointer;
}

stack_item *pop()
{
    if (stack_pointer == null)
    {
     printf("error: stack is empty.\r\n");
     return null;
    }

    stack_item *current = stack_pointer;
    stack_pointer = current->parent;

    return current;
}

Mind that a spaghetti stack is useful when you want to keep references of things that you pop out of the stack, having many parallel linked list that end to a common root. So you have to keep references of item you pop out because you need to traverse them in a bottom-up way from the leaf to the root, and of course using a different leaf node will produce a different linked list that has elements in common with other lists that start from other leaves..

Jack
what's cur? you never defined what that is...
Ralph
shouldn't the push_parallel function return a pointer to the top of the stack?
Ralph
cur is just an error due to stack_pointer that was called in a different way, I fixed it. For the push_parallel function it depends, the fact is that a spaghetti stack doesn't really have ONE top of the stack but many according from where you start to visit it, usually you have to care about references outside the stack by yourself.
Jack