开发者

Stack implemented via a linked-list in C

The following code is part of a stack implementation, implemented via a linked-list, in C. Are there problems with the code? Specifically, in the pop() method the caller passes a void** argument so pop() can assign a pointer to the top node's data to it. pop() subsequently calls delete to free the stack's top node, which is where *data is pointing. Won't this delete the data in the pointer that should be returned to the caller, or am I missing something?

typedef struct Element 
{
    struct Element *next;
    void *data;
} Elemen开发者_如何学JAVAt;


bool pop( Element **stack, void **data )
{
    Element *elem;
    if (!(elem = *stack)) return false;

    *data = elem->data;
    *stack = elem->next;
    delete elem;
    return true;
}


bool push( Element **stack, void *data )
{
    Element *elem = new Element;
    if(!elem) return false;

    elem->data = data;
    elem->next = *stack;
    *stack = elem;
    return true;
} 


A few thoughts:

  • If you want to compile this with a C compiler, use malloc() and free() instead of new and delete. Those are C++ keywords.
  • If you need a quick way to determine the size of the stack, I suggest making a Stack data structure that holds the head and tail pointers and the stack's length, then pass that into your push() and pop() functions. On top of that, you won't need double pointers.
  • Return the data pointer from your pop() function and don't forget to free() it (if necessary).


The pop implementation is okay as is. The Element structure and data pointer are two separate chunks of memory. Deleting the list element does not delete the data pointed to by its member. You can see that maybe more clearly in the push function. It creates a new Element and sets its data pointer to the given memory.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜