Article 84 - Data Structure - How to Implement Stack in C

This article describes an implementation of the Stack Structure.

For information about the Stack Structure, see Article 31 - Programming Data Structures.

To program a Stack, we need to understand the interface of a Stack.

Interface

  • Push Function
  • Pop Function
  • Is Empty Function

Implementation

In this implementation, we use the Node structure from the Link List Article, see Article 83 - Data Structure - How to Implement Linked List in C.

Push Function

The Push Function adds an item to the Stack, the item goes on top of the Stack. We can use a linked list to implement a Stack and append/remove from the head of the list.

For information about the Linked List Structure, see Article 83 - Data Structure - How to Implement Linked List in C.

A function to push a node onto the Stack.

int push( Node ** stack, int content ){
    Node * node;
    
    if( !stack ){
        return -1;
    }

    node = newNode( content );

    if( !node ){
        return -2;
    }

    return addNode( stack, node );
}

Pop Function

Simply remove the node at the head of the list and return it, or return error if the list is empty.

A function to pop a node from the Stack.

int pop( Node ** stack, int * content ){   
    if( !stack || !content ){
        return -1;
    }   

    if( !*stack ){
        return -2;
    }

    *content = (*stack)->content;

    return removeNode( stack, *stack );
}

Is Empty Function

Checking if the list is empty or null will determine if the Stack contains anything or not.

A function determine if the Stack is empty.

int isEmpty( Node * stack ){
    if( !stack ){
        return -1;
    }

    if( !*stack ){
        return 0;
    }

    return 1;
}

Comments (12)

Posted by anonymous - bookmaring service at Friday, March 15, 2013 12:27 AM

sLq01Q I cannot thank you enough for the blog article.Really thank you! Keep writing.

Posted by anonymous - buy cipro at Friday, March 15, 2013 10:56 AM

A round of applause for your blog.Thanks Again. Cool.

Posted by anonymous - generic viagra online at Friday, March 15, 2013 12:34 PM

Major thankies for the post. Really Cool.

Posted by anonymous - cheap cialis at Friday, March 15, 2013 2:14 PM

Muchos Gracias for your article.Really looking forward to read more. Really Great.

Posted by anonymous - Buy Levitra online uk at Friday, March 15, 2013 3:54 PM

Very informative article post.Much thanks again. Really Cool.

Post a comment

  • Name:
  • Post:
  • Challenge:

Register or login to post comments easier.


Vantasy World Copyright 2011 - 2017. Vantasy World is a project developed by Vantasy Online. Privacy Policy.