Stack implementation can be done in three ways .
I discussed the first one ie with the help of linked list in my previous blog
lets with the help of stack implementation with dynamic array
#include<stdio.h>
struct node1{
int value ;
struct node *next;
};
typedef struct node1 node;
void push (int **topptr, int data)
{
node *newnode= (node*)malloc(sizeof(node));
newnode->value= data ;
{
newnode->next = *topptr;
*topptr= newnode;
}
}
int pop(int **topptr)
{
int x;
if(*topptr==NULL)
{
printf("the stack is already empty");
}
else
{
x=**topptr;
node *tmp= *topptr;
*topptr= tmp->next;
free(tmp);
}
return x;
}
void print(node *hp)
{
if(hp==NULL)
{
printf("list is empty");
}
while(hp!=NULL)
{
printf("%d\n",hp->value);
hp=hp->next;
}
}
void main()
{
node *top=NULL;
push (&top,10);
push (&top,11);
push (&top,15);
push (&top,7);
print(top);
pop(&top);
print(top);
}
I discussed the first one ie with the help of linked list in my previous blog
lets with the help of stack implementation with dynamic array
#include<stdio.h>
struct node1{
int value ;
struct node *next;
};
typedef struct node1 node;
void push (int **topptr, int data)
{
node *newnode= (node*)malloc(sizeof(node));
newnode->value= data ;
{
newnode->next = *topptr;
*topptr= newnode;
}
}
int pop(int **topptr)
{
int x;
if(*topptr==NULL)
{
printf("the stack is already empty");
}
else
{
x=**topptr;
node *tmp= *topptr;
*topptr= tmp->next;
free(tmp);
}
return x;
}
void print(node *hp)
{
if(hp==NULL)
{
printf("list is empty");
}
while(hp!=NULL)
{
printf("%d\n",hp->value);
hp=hp->next;
}
}
void main()
{
node *top=NULL;
push (&top,10);
push (&top,11);
push (&top,15);
push (&top,7);
print(top);
pop(&top);
print(top);
}
No comments:
Post a Comment