How to implement stacks in c++?

Introduction to arrays as class member data

How to implement stacks in c++?  How arrays are used as data members of Class?  So far it is seen only the variables and functions can be used as members of a class. But arrays can also be used as data members of a class. An application of this is the implementation of stacks. Before understanding how it is done lets have a brief introduction of stack.

How to implement stacks in c++?

stacks are special data structures that are used for storing and then removing data items from the memory. Stacks work on the LIFO (last in first out) principal. The simple example is piling up the plates and then removing the one from the top. It means the plate that was stored at last is removed at first. Generally speaking in computers engineering terms whenever the control of a program is transferred from one address to another, the address to be returned at is stored in stack. Similarly when a function is called, the control of program is transferred to the definition of the function. In order to maintain the sequence of the program the address of the next instruction from where the call was made is stored in stack. There are many examples that show the significance of stack in computer programming. Consider the following example which shows how arrays as class members implement stack.

Example

class stack

{

private:

enum {max=10};

int st[max];

int top;

public:

stack()

{

top=0;

}

void push(int var)

{

st[++top]=var;

}

int pop()

{
return st[pop–];

}

};

void main()

{
clrscr();

stack s1;

s1.push(11);

s1.push(22);

cout<<“1: “<<s1.pop()<<endl;

cout<<“2: “<<s2.pop()<<endl;

s1.push(33);

s1.push(44);

s1.push(55);

s1.push(66);

cout<<“3:”<<s1.pop()<<endl;

cout<<“4:”<<s1.pop()<<endl;

cout<<“5:”<<s1.pop()<<endl;

cout<<“6:”<<s1.pop()<<endl;

}

when a value is stored in a stack it is called pushing and when a data item is removed from the stack it is called popping. The above program uses an object s1 for pushing two values in the stack and then pops off them. Then four more data items are pushed and popped off from the stack. It is to remember that the items are always popped off in the reverse order: last pushed first popped.

Also read here

2 thoughts on “How to implement stacks in c++?”

Leave a Reply

Your email address will not be published.