Friday, October 16, 2009

Simple Linked Stack

#include
#include
struct node{
        int val;
        struct node *next;
};

void push(struct node**);
void pop(struct node**);

int main()
{
  struct node *head=NULL;
  int opt=0;

   while(1){
          printf("Select an option \n 1.Push 2.Pop 3.Exit\n");
          scanf("%d",&opt);
          switch(opt){
          case 1:{push(&head); break; }
          case 2:{pop(&head);break;}
          case 3:{ exit(0); }
        }
     }
}
void push(struct node **head)          //to insert at begining
{                                                         //input is address of head
   struct node *ptr;

   ptr=(struct node*)malloc(sizeof(struct node));
   if(ptr==NULL){
      printf("Allocation failed\n");
      return;
   }
    printf("Enter an integer value\n");
    scanf("%d",&ptr->val);
    ptr->next=*head;
    *head=ptr;

}


void pop(struct node **head)              //to pop an element out
{                                                         //input is address of head    if(*head==NULL){
        printf("\n Stack Empty\n");
        return;
    }
    struct node *ptr;
    ptr=*head;
    printf("the poped value is%d\n",ptr->val);
    *head=ptr->next;
     free(ptr);
}

No comments:

Post a Comment