Stack using linked list

Logic


Push

If top==NULL
    Just allocate memory and data for top node.Make top->next = NULL.
else
    Allocate memory and data for current node.
    Let next of current node point to top.
    Make current node as top.
    Push 1   

                           |_____|
                     top-->|__1__|

                            _______
                     top-->| 1 | --|---->NULL
                           |___|___|
    Push 2


                     top-->|__2__|
                           |__1__|


                            top
                             |
                            \|/
                           _______       ______
                          | 2 | --|---->| 1 | -|-->NULL
                          |___|___|     |___|__|

    Push 3
                    top-->|__3__|  
                          |__2__|
                          |__1__|

                            top
                             |
                            \|/
                          _________      _______       ______
                         |  3 | --|---->| 2 | --|---->| 1 | -|-->NULL
                         |____|___|     |___|___|     |___|__|

void push(int element)
{
    node* curr;

    if(isEmpty())
    {
        top = (node*)malloc(sizeof(node));
        top->data = element;
        top->next = NULL;
    }
    else
    {
        curr = (node*)malloc(sizeof(node));
        curr->data = element;
        curr->next = top;
        top = curr;
    }
}


Pop

Let current node point to next of top.
Deallocate memory for node pointed by top.
Make current node as top.                   

3 is popped out
                                     |_____|
                               top-->|__2__|
                                     |__1__|              



                                    top            curr
                                     |              | 
                                    \|/            \|/
                                  _________      _______       ______
                                 |  3 | --|---->| 2 | --|---->| 1 | -|-->NULL
                                 |____|___|     |___|___|     |___|__|


                                                    top
                                                     |
                                                    \|/
                                                 _________     ________
                                                 | 2 | --|---->| 1 | -|-->NULL
                                                 |___|___|     |___|__|

void pop()
{
    node* curr;

    if(isEmpty())
        printf("Stack is empty.Can't pop");
    else
    {   
        curr=top->next;

        free(top);

        top=curr;
    }
}   



No comments:

Post a Comment