Wednesday, 12 February 2014

Stack using linked list cprogram

Aim: Stack Using Linked List In Cprogram

Program:

#include<stdio.h>

#include<conio.h>

#include<alloc.h>

void push(int);

void pop();

void display();

struct list

{

int data;

struct list *next;

};

typedef struct list node;

node *header,*top;



void main()

{

int ch,item;

clrscr();

header=(node *)malloc(sizeof(node));

header->data=NULL;

header->next=NULL;

top=header->next;

while(1)

{

printf("1.push\t 2.pop\t 3.display\t 4.exit\n");

printf("enter your choice\n");

scanf("%d",&ch);

switch(ch)

{

case 1:

printf("enter the item you want to push\n");

scanf("%d",&item);

push(item);

break;

case 2:

pop();

break;

case 3:

display();

break;

default:

exit(0);

}

}

}

void push(int item)

{

node *new;

new=(node *)malloc(sizeof(node));

new->data=item;

new->next=top;

top=new;

header->next=new;

}

void pop()

{

top=header->next;

if(top==NULL)

printf("underflow\n");

else

{

header->next=top->next;

free(top);

top=header->next;

}

}

void display()

{

node *ptr;

ptr=header->next;

printf("header->");

while(ptr!=NULL)

{

printf("%d->",ptr->data);

ptr=ptr->next;

}

printf("NULL\n");


}

Output:


No comments:

Post a Comment