Program Discussion :: Stack
88 / 5
Write a push() and pop() implementation using linked list in C.
Answer:
#include
#include
#include
using namespace std;
struct node
{
int info;
struct node *ptr;
}*top,*top1,*temp;
void push(int data);
void pop();
void create();
int count = 0;
void main()
{
int no, ch, e;
coutinfo);
free(top);
top = top1;
count--;
}
Asked In ::
Language:
Vishal Rai
7 Jul, 2017 9:30 AM
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *ptr;
}*top,*top1,*temp;
void push(int data);
void pop();
void create();
int count = 0;
void main()
{
int no, ch, e;
printf("\n 1 - Push");
printf("\n 2 - Pop");
create();
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
push(no);
break;
case 2:
pop();
break;
default :
printf(" Wrong choice, Please enter correct choice ");
break;
}
}
}
void create()
{
top = NULL;
}
/* Count stack elements */
void stack_count()
{
printf("\n No. of elements in stack : %d", count);
}
/* Push data into stack */
void push(int data)
{
if (top == NULL)
{
top =(struct node *)malloc(1*sizeof(struct node));
top->ptr = NULL;
top->info = data;
}
else
{
temp =(struct node *)malloc(1*sizeof(struct node));
temp->ptr = top;
temp->info = data;
top = temp;
}
count++;
}
void pop()
{
top1 = top;
if (top1 == NULL)
{
printf("\n Error : Trying to pop from empty stack");
return;
}
else
top1 = top1->ptr;
printf("\n Popped value : %d", top->info);
free(top);
top = top1;
count--;
}
Language:
Vignesh
7 Jul, 2017 9:30 AM
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
struct node
{
int info;
struct node *ptr;
}*top,*top1,*temp;
void push(int data);
void pop();
void create();
int count = 0;
void main()
{
int no, ch, e;
cout<<"\n 1 - Push";
cout<<"\n 2 - Pop";
create();
while (1)
{
cout<<"\n Enter choice : ";
cin>>ch;
switch (ch)
{
case 1:
cout<<"Enter data : ";
cin>>no;
push(no);
break;
case 2:
pop();
break;
default :
cout<<" Wrong choice, Please enter correct choice ";
break;
}
}
}
void create()
{
top = NULL;
}
/* Count stack elements */
void stack_count()
{
printf("\n No. of elements in stack : %d", count);
}
/* Push data into stack */
void push(int data)
{
if (top == NULL)
{
top =(struct node *)malloc(1*sizeof(struct node));
top->ptr = NULL;
top->info = data;
}
else
{
temp =(struct node *)malloc(1*sizeof(struct node));
temp->ptr = top;
temp->info = data;
top = temp;
}
count++;
}
void pop()
{
top1 = top;
if (top1 == NULL)
{
printf("\n Error : Trying to pop from empty stack");
return;
}
else
top1 = top1->ptr;
printf("\n Popped value : %d", top->info);
free(top);
top = top1;
count--;
}