facebook like button

31 July, 2011

program 69: stack implementation of linked list

The need:
    This program was written to get clear idea of stack concept. When I wrote program of previous post, I used to try to find physical existence of stack in the program. This program shows that stack is just an implementation not a physical thing like array. This program utilizes two common UDFs of stack implementation: 1. push() 2. pop(). This program only takes an element( here a number) form user and pushes on the top of an abstract stack. Then the program pops that element and prints back for user.
The code:
------------------------------------------------------
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MIN_INT 0x80000000
struct linked_list
{
int num;
struct linked_list *next;
};
typedef struct linked_list node;
void push(node **p,int x);
int pop(node **p);
main()
{
    int i,j;
    node *top=NULL;
    printf("Enter a natural number to push on stack.\n");
    scanf("%d",&i);
    push(&top,i);
    printf("%d pushed successfully\n",i);
    printf("now popping\n");
    j=pop(&top);
    printf("element popped is %d\n",j);
    return 0;
}
void push(node **p,int x)
{
    node *new_node;
    new_node=(node *)malloc(sizeof(node));
    new_node->num=x;
    new_node->next=*p;
    *p=new_node;
}
int pop(node **p)
{
    node *tmp=*p;
    int temp;
    if(tmp==NULL)
        return (MIN_INT);
    else
    {   
        *p=tmp->next;
        temp = tmp->num;
        free(tmp);
        return(temp);
    }
}
------------------------------------------------------
Remarks:
1. This program can be used for pushing any number of values. Here I needed some indication when the empty stack is asked for pop. In that case pop returns MIN_INT which is minimum possible value for integer. When on popping stack returns MIN_INT in main, we get to know that stack is actually empty.
2. Have a look on this program for some purposeful implementation of stack concept.

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply