Stack Implementation using Linked List

// Dynamic Implementation of Stack

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

void push(int);

void pop();

void display();

void peek();

struct node{

int data;

struct node *next;

};

struct node *newnode, *top=0,*temp;

void main(){

push(3);

push(5);

push(7);

push(9);

display();

peek();

pop();

display();

peek();

getch();

}

void push(int x){

newnode=(struct node*)malloc(sizeof(struct node));

newnode->data=x;

newnode->next=top;

top=newnode;

}

void display(){

temp=top;

if(top==0)

printf("Stack is empty.");

else{

printf("Current elements of stack:\n");

while(temp!=0){

printf("%d\n",temp->data);

temp=temp->next;

}

}

}

void peek(){

if(top==0)

printf("Stack is empty.");

else

printf("Top element is %d",top->data);

}

void pop(){

temp=top;

if(top==0)

printf("Stack is empty.");

else{

printf("\nPopped out: %d\n",top->data);

top=top->next;

free(temp);

}

}


 

No comments:

Post a Comment