Saturday, August 31, 2013

Simple stacks implementation using linked list : PUSH , POP

/*simple stacks implementation using linked list */

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>

struct stack
 {
int data;
  struct node *link;
 };
void push(struct stack **top,int val)
 {
  struct stack *temp;
  temp =(struct stack *)malloc(sizeof(struct stack));
  if(temp==NULL)
  printf("\nstack overflow\n");
temp->data=val;
temp->link=*top;
*top=temp;
 }
int pop(struct stack **top)
 {
  struct stack *temp;
  int ret;
  if(*top==NULL)
  {
  printf("\nstack underflow\n");
  return NULL;
  }
  temp=*top;
  ret=temp->data;
  (*top)=(*top)->link;
  free(temp);
  return ret;
 }

void main()
 {
  struct stack *s1=NULL;
  int i;
 
  push(&s1,12);
  push(&s1,20);
  push(&s1,1);
  push(&s1,13);
 
  i=pop(&s1);          // i=13
  i=pop(&s1);          // i=1
 
  printf("%d\n",i);   // prints 1
 }


No comments: