write a program in c++ to implement stack using functions
in header file stack.h

Answer Posted / sachindra bagchi

Implementing Stack using Class (with constructor etc).

# include<iostream.h>
# include<conio.h>
# define SIZE 20

class stack
{
int a[SIZE];
int tos; // Top of Stack
public:
stack();
void push(int);
int pop();
int isempty();
int isfull();
};
stack::stack()
{
tos=0; //Initialize Top of Stack
}

int stack::isempty()
{
return (tos==0?1:0);
}
int stack::isfull()
{
return (tos==SIZE?1:0);
}

void stack::push(int i)
{

if(!isfull())
{
cout<<"Pushing "<<i<<endl;
a[tos]=i;
tos++;
}
else
{
cerr<<"Stack overflow error !
Possible Data Loss !";
}
}
int stack::pop()
{
if(!isempty())
{
cout<<"Popping "<<a[tos-1]<<endl;
return(a[--tos]);
}
else
{
cerr<<"Stack is empty! What to pop...!";
}
return 0;
}

void reverse(stack s)
{
stack s2;
while(!s.isempty())
{
s2.push(s.pop());
}
cout<<"Reversed contents of the stack..."<<endl;
while(!s2.isempty())
{
cout<<s2.pop()<<endl;
}
}//end of fn.
void main()
{
clrscr();
stack s;

s.push(1);
s.push(2);
s.push(3);

reverse(s);
getch();
}

Is This Answer Correct ?    30 Yes 32 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Differentiate between a copy constructor and an overloaded assignment operator.

839


What is cout flush?

753


Carry out conversion of one object of user-defined type to another?

795


Where the memory to the static variables is allocated?

766


Write syntax to define friend functions in C++.

810


What type of question are asked in GE code writing test based on c++ data structures and pointers?

3700


How do I use arrays in c++?

758


What number of digits that can be accuratly stored in a float (based on the IEEE Standard 754)? a) 6 b) 38 c) An unlimited number

1002


write a function signature with various number of parameters.

789


What is data type in c++?

757


Is there any function that can skip certain number of characters present in the input stream?

786


What is the insertion operator and what does it do?

784


In which header file does one find isalpha() a) conio.h b) stdio.h c) ctype.h

954


Evaluate as true or false: !(1 &&0 || !1) a) True b) False c) Invalid statement

839


Write about the members that a derived class can add?

757