Sunday, 17 August 2014

IMPLEMENTING STACK VIA LINKED-LIST 

We all know what stack do . Its follows a  Last In First Out methodology and here in this program i have implemented the same via LinkedList . I hope you all know what a LinkedList does . 
struct node
{
  node *next ;
  int data ;
};
struct node *head = NULL , *p=NULL ;
void display()
{
  node *temp = new node() ;
  temp = head ;
  while(temp!=NULL)
  {
    printf("%d\n",temp->data) ;
    temp = temp->next ;
  }
}
void push(int x)
{
  node *nd = new node() ;
  nd->data = x ;
  if(head==NULL)
  {
    head = p = nd ;

  }else
  {
    p->next  = nd ;
    p = p->next ;
  }
  display() ;
}
void pop ()
{
  node *temp = new node() ;
  temp = head ;
  while(temp->next->next!=NULL)
  {
      temp = temp->next ;
  }
  printf("popped element %d\n",temp->next->data) ;
  temp->next = NULL ;
  display() ;
}
int _tmain(int argc, _TCHAR* argv[])
{
    int value , x , v ;
    do
    {
        printf("1. push") ;
        printf("2. pop");
        printf("choose...") ;
        scanf_s("%d",&value) ;
        switch(value)
        {
        case 1 :
            printf("Enter data");
            scanf_s("%d",&x);
            push(x) ;
            break;
        case 2 :
            pop() ;
        }
        printf("press 3 to continue") ;
        scanf_s("%d",&v) ;
    }while(v==3) ;

    return 0;
}
 

No comments:

Post a Comment