Stack and QUEUE
Stack and QUEUE
In Computer Science, a data structure is a particular way of storing and organizing data in a
computer so that it can be used efficiently. Different kinds of data structures are suited to
different kinds of applications, and some are highly specialized to specific tasks.
Stack
In computer science, a stack is a last in, first out (LIFO) data structure. A stack can is
characterized by only two fundamental operations: push and pop. The push operation adds
an item to the top of the stack. The pop operation removes an item from the top of the stack,
and returns this value to the caller.
A stack is a restricted data structure, because only a small number of operations are
performed on it. The nature of the pop and push operations also mean that stack elements
have a natural order. Elements are removed from the stack in the reverse order to the order
of their addition: therefore, the lower elements are those that have been on the stack the
longest. One of the common uses of stack is in function call.
After first s1.pop() statement, the item 5 is removed from the stack and top moves from 1 to 0
4
3
2
1
top 0 3
After second s1.pop() statement, the item 3 is removed from stack and top moves from 0 to -
1 which indicates that now stack is empty.
4
3
2
1
0
top -1
After third s1.pop() statement the pop function display error message “stack is empty” and
returns -1 to indicating that stack is empty and do not change the position of top of the stack.
Stack using Linked list
In Computer Science, a linked list (or more clearly, "singly-linked list") is a data structure that
consists of a sequence of nodes each of which contains data and a pointer which points (i.e.,
a link) to the next node in the sequence.
A linked list whose nodes contain two fields: an integer value and a link to the next node
The main benefit of a linked list over a conventional array is that the list elements can easily
be added or removed without reallocation or reorganization of the entire structure because the
data items need not be stored contiguously in memory or on disk .Stack using linked lists allow
insertion and removal of nodes only at the position where the pointer top is pointing to.
#include<iostream.h>
struct node
{
Int item; //data that will be stored in each node
node * next; //pointer which contains address of another node
}; //node is a self referential structure which contains reference of another object type node
class stack
{node *top;
public:
stack() //constructor to create an empty stack by initializing top with NULL
{ top=NULL; }
void push(int item);
int pop();
~stack();
};
void stack::push(int item) //to insert a new node at the top of the stack
{node *t=new node; //dynamic memory allocation for a new object of node type
if(t==NULL)
cout<<”Memory not available, stack is full”;
else
{t->item=item;
t->next=top; //newly created node will point to the last inserted node or NULL if
//stack is empty
top=t; //top will point to the newly created node
}
}
int stack::pop()//to delete the last inserted node(which is currently pointed by the top)
{if(top==NULL)
{cout<<”Stack is empty \n”;
return 0; // 0 indicating that stack is empty
}
else
{node *t=top; //save the address of top in t
int r=top->item; //store item of the node currently pointed by top
top=top->next; // move top from last node to the second last node
delete t; //remove last node of the stack from memory
return r;
}
}
stack::~stack() //de-allocated all undeleted nodes of the stack when stack goes out of scope
{node *t;
while(top!=NULL)
{t=top;
top=top->next;
delete t;
}
};
void main()
{ stack s1;
s1.push(3);
s1.push(5);
s1.push(7);
cout<<s1.pop()<<endl;
cout<<s1.pop()<<endl;
cout<<s1.pop()<<endl;
cout<<s1.pop()<<endl;
}
Output is
7
5
3
Stack is empty 0
In the above program the statement stack s1; invokes the constructor stack() which create an
empty stack object s1 and initialize top with NULL.
top NULL
After statement s1.push(3) the stack become
top 3 NULL
top 5 3 NULL
top 7 5 3 NULL
After the first s1.pop() statement the node currently pointed by top (i.e. node containing 7) is
deleted from the stack, after deletion the status of stack is
top 5 3 NULL
After the second s1.pop() statement the node currently pointed by top (i.e. node containing 5)
is deleted from the stack, after deletion the status of stack is
top NULL
After the third s1.pop() statement the node 3 currently pointed by top (i.e.
node containing 3) is deleted from the stack, after deletion the stack become
empty i.e.
Top NULL
After the fourth s1.pop() statement, the error message “stack is empty“ displayed and the pop()
function return 0 to indicate that stack is empty.
For example convert the infix expression (A+B)*(C-D)/E into postfix expression showing stack
status after every step.
Symbol scanned from infix Stack status ( bold letter Postfix expression
shows the top of the stack)
(
( ((
A (( A
+ ((+ A
B ((+ AB
) ( AB+
* (* AB+
( (*( AB+
C (*( AB+C
- (*(- AB+C
D (*(- AB+CD
) (* AB+CD-
/ (/ AB+CD-*
E (/ AB+CD-*E
) AB+CD-*E/
Answer: Postfix expression of (A+B)*(C-D)/E is AB+CD-*E/
Example: Evaluate the following postfix expression showing stack status after every step
8, 2, +, 5, 3, -, *, 4 /
token scanned Stack status ( bold letter Operation performed
from postfix shows the top of the
expression stack) after processing
the scanned token
8 8 Push 8
2 8, 2 Push 2
+ 10 Op2=pop() i.e 2
Op1=pop() i.e 8
Push(op1+op2) i.e. 8+2
5 10, 5 Push(5)
3 10, 5, 3 Push(3)
- 10, 2 Op2=pop() i.e. 3
Op1=pop() i.e. 5
Push(op1-op2) i.e. 5-3
* 20 Op2=pop() i.e. 2
Op1=pop() i.e. 10
Push(op1-op2) i.e. 10*2
4 20, 4 Push 4
/ 5 Op2=pop() i.e. 4
Op1=pop() i.e. 20
Push(op1/op2) i.e. 20/4
NULL Final result 5 Pop 5 and return 5
Example:
Evaluate the following Boolean postfix expression showing stack status after every step
True, False, True, AND, OR, False, NOT, AND
Queue
Queue is a linear data structure which follows First In First Out (FIFO) rule in which a new item
is added at the rear end and deletion of item is from the front end of the queue. In a FIFO data
structure, the first element added to the queue will be the first one to be removed.
#include<iostream.h>
const int size=5;
class queue
{int front , rear;
int a[size];
public:
queue(){frot=0;rear=0;} //Constructor to create an empty queue
void addQ()
{ if(rear==size)
cout<<”queue is full<<endl;
else
a[rear++]=item;
}
int delQ()
{if(front==rear)
{cout<<”queue is empty”<<endl; return 0;}
else
return a[front++];
}
}
void main()
{queue q1;
q1.addQ(3);
q1.addQ(5) ;
q1.addQ(7) ;
cout<<q1.delQ()<<endl ;
cout<<q1.delQ()<<endl ;
cout<<q1.delQ()<<endl;
cout<<q1.delQ()<<endl;
}
Output is
3
5
7
Queue is empty
0
In the above program the statement queue q1 creates an empty queue q1.
Front
Rear
After execution of the statement q1.addQ(3), status of queue is
Front
Rear
After execution of the statement q1.addQ(5), status of queue is
Front
Rear
After execution of the statement q1.addQ(7), status of queue is
Front
Rear
After execution of the first cout<<q1.delQ() statement, 3 is deleted from queue status of queue
is
Front
Rear
After execution of the second cout<<q1.delQ() statement, 5 is deleted from the queue status
of queue is
Front
Rear
After execution of the fourth cout<<q1.delQ() statement, the message “queue is empty“
displayed and status of queue is Front
3 NULL
rear
After statement q1.addQ(5) the stack become
front
3 5 NULL
rear
After statement q1.addQ(7) the stack become
front
3 5 7 NULL
rear
After the first q1.delQ() statement the node currently pointed by front (i.e. node containing 3)
is deleted from the queue, after deletion the status of queue is
front
5 7 NULL
rear
After the second q1.delQ() statement the node currently pointed by front (i.e. node containing
5) is deleted from the queue, after deletion the status of queue is
front
7 NULL
rear
After the third q1.delQ() statement the node currently pointed by front (i.e. node containing 7)
is deleted from the queue, after deletion the queue become empty therefore NULL is a
assigned to both rear and front
front
NULL
rear
After the fourth q1.delQ() statement, the error message “queue is empty“ displayed and the
pop() function return 0 to indicate that queue is empty.
57. Translate,
following infix
expression into
its equivalent
postfix
expression: ((A-
B)*(D/E))/(F*G*H)
Ans 57. Equivalent postfix expression:
=((A-B)*(D/E))/(F*G*H)
=((AB-)*(DE/))/(FG*H*)
=AB – DE /* FG* H*/
58. Translate, following infix expression into its equivalent
postfix expression: A*(B+D)/E-F-(G+H/K)
Ans 58. Equivalent postfix expression:
= A*(B+D)/E-F-(G+H/K)
= (A*(B+D)/E) – (F – (G + (H/K)))
= (A*(BD+)/E) – (F – (G + (HK/)))
= ((ABD+*) / E) – (F – (GHK/+))
= ABD+* E/F – GHK/+ -
59. Write the equivalent infix expression for 10,3,*,7,1,-
,*,23,+
Ans 59. 10 * 3 * (7 – 1) + 23
63. Give postfix form expression for: NOT A OR NOT B AND NOT
C
Ans 63. =((A NOT) OR ((B NOT) AND (C NOT)))
=((A NOT) OR ((B NOT C NOT AND))
=A NOT B NOT C NOT AND OR
64. Consider the infix expression Q : A+B * C ↑ (D/E)/F.
Translate Q into P, where P is the postfix equivalent
expression of Q. what will be the result of Q if this
expression is evaluated for A, B, C, D, E, F as 2, 3, 2, 7, 2,
2 respectively.
Ans 64. P = ABCDE/^*F/+
2,3,2,7,2
2,3,2->7/2->3
2,3,2,3
2,3->2^3->8
2,3,8
2->3*8->24
2,24,2
2->24/2->12
2,12
2+12
Result of evaluation = 14
78. Write the definition of a member function Pop() in C++, to delete a book
from a dynamic stack of TEXTBOOKS considering the following code is already
included in the program.
struct TEXTBOOKS
{
char ISBN[20]; char TITLE[80];
TEXTBOOKS *Link;
};
class STACK
{
TEXTBOOKS *Top;
public:
STACK() {Top=NULL;}
void Push();
void Pop();
~STACK();
};
Ans 78. void STACK::POP()
{
if (Top!=NULL)
{
TEXTBOOKS *Temp;
Temp=Top;
cout<<Top->ISBN<<Top->TITLE<<”deleted”<<endl;
Top=Top>
Link;
delete Temp;
}
else
cout<<”Stack Empty”<<endl;
}
79. Write the definition of a member function PUSH() in C++, to add a new book
in a dynamic stack of BOOKS considering the following code is already included in
the program:
struct BOOKS
{
char ISBN[20], TITLE[80];
BOOKS *Link;
};
class STACK
{
BOOKS *Top;
public:
STACK()
{Top=NULL;}
void PUSH();
void POP();
~STACK();
};
Ans 79. void STACK::PUSH()
{
BOOKS *Temp;
Temp=new BOOKS;
gets(Temp->ISBN);
gets(Temp->TITLE);
Temp->Link=Top;
Top=Temp;
}
80. Write a complete program in c++ to implement a
dynamically allocated Stack containing names of Countries.
Ans 80. #include<iostream.h>
#include<stdio.h>
struct Node
{ char Country [20] ; Node *Link; };
class Stack
{ Node *Top;
public:
Stack( )
{ Top = NULL; }
void Push() ;
void Pop() ;
void Display() ;
~Stack () ;
};
void Stack::Push( )
{
Node *Temp = new Node;
gets(Temp -> Country);
Temp -> Link = Top;
Top = Temp;
}
void Stack::Pop( )
{
if (Top !=NULL)
{
Node *Temp = Top;
Top = Top -> Link;
delete Temp;
}
else
cout<<“stack Empty”;
}
void Stack::Display( )
{
Node *Temp = Top;
while (Temp! = NULL)
{
cout<<Temp -> Country <<endl;
Temp = Temp -> Link;
}
}
Stack::~Stack ( )
{
while (Top!=NULL)
{ NODE *Temp=Top;
Top=Top->Link;
delete Temp;
}
}
void main ( )
{ Stack ST;
char Ch;
do
{ cout<<“p/O/D/Q” ;
cin>>Ch;
switch (Ch)
{
case ‘P’ : ST.Push( ); break;
case ‘O’ :ST.Pop(); break;
case ‘D’ :ST.Disp();
}
} while (Ch!=’Q’);
}
81. Write a complete program in C++ to implement a
dynamically allocated Queue containing names of Cities.
Ans 81. #include <iostream.h>
#include <conio.h>
struct NODE
{ char City[20];
NODE *Next;
};
class Queue
{ NODE *Rear,*Front;
puplic:
Queue( )
{ Rear=NULL;Front=NULL;
}
void Qinsert( );
void Qdelete( );
void Qdisplay( );
~Queue( );
} ;
void Queue::Qinsert( )
{
NODE *Temp;
Temp=new NODE;
cout<<”Data:”;
gets (Temp->City);
Temp->Next=NULL;
if (Rear==NULL)
{
Rear=Temp;
Front=Temp;
}
else
{
Rear–>Next=Temp;
Rear=Temp;
}
}
void Queue::Qdelete( )
{
if (Front!=NULL)
{
NODE *Temp=Front;
cout<<Front->City<<”Deleted \n”;
Front=Front->Next;
delete Temp;
if (Front==NULL)
Rear=NULL;
}
else
cout<<”Queue Empty..”;
}
Queue:: Qdisplay( )
{ NODE *Temp=Front;
while (Temp!=NULL)
{
cout<<Temp->City<<endl;
Temp=Temp->Next;
}
}
Queue:: ~Queue( )//Destructor Function
{ while (Front!=NULL)
{ NODE *Temp=Front;
Front=Front->Next; delete Temp;
}
}
void main( )
{ Queue QU;
char Ch;
do
{
:
:
} while (Ch!=’Q’);
}
82. Write a function QUEINS( ) in C++ to insert an element in
a dynamically allocated Queue containing nodes of the
following given structure:
struct Node
{ int PId ; //Product Id
char Pname [20] ;
NODE *Next ;
} ;
ANs 82. void QUEINS (Node *&Front, Node *&Rear)
{ Node *Temp = new Node;
cin>>Temp->PId;
gets (Temp->Pname);
//or cin>>Temp->Pname;
//cin.get1ine(Temp->Pname);
Temp->Next = NULL;
if(Rear == NULL)
Front = Temp;
e1se
Rear -> Next = Temp;
Rear = Temp;
}
83. Write a function QUEDEL( ) in C++ to display and delete
an element from a dynamically allocated Queue containing nodes
of the following given structure:
struct NODE
{
int Itemno;
char Itemname[20];
NODE *Link;
} ;
Ans 83. class Queue
{ Node *Front, *Rear;
public:
QUEUE( )//Constructor to initialize Front and Rear
{
Front = NULL;
Rear = NULL;
}
void QUEINS( ); //Function to insert a node
void QUEDEL( ); //Function to delete a node
void QUEDISP( ); //Function to display nodes
~Queue(); //Destructor to delete all nodes
};
void Queue::QUEDEL( )
{ if (Front!=NULL)
{NODE *Temp=Front;
cout<<Front->Itemno<<” “;
cout<<Front->Itemname<<”Deleted“;
Front=Front->Link;
delete Temp;
if (Front NULL)
Rear=NULL;
}
else
cout<<”Queue Empty..”;
}
84. Write a function in C++ to delete a node containing
Book’s information, from a dynamically allocated Stack of
Books implemented with the help of the following structure.
struct Book
{
int BNo ;
char BName[20] ;
Book *Next ;
} ;
Ans 84. struct Book
{
int BNo ;
char BName[20] ;
Book *Next ;
} ;
class Stack
{
Book *Top;
public:
Stack( )
{
Top = NULL;
}
void Push( );
void Pop( );
void Display( );
};
void Stack::Pop( )
{
Book *Temp;
if( Top= = NULL)
cout<<”Stack Underflow…”;
else
{
cout<<”\nThe Book number of the
element to delete: “<<Top->BNo;
cout<<”\nThe Book name of the
element to delete: “<<Top->BName;
Temp=Top;
Top=Top->Next;
delete Temp;
}
}
};
Ans 87. void QINSERT()
{ NODE *P=new NODE();
cout<<"Enter the client number";
cin>>P->Cno;
cout<<"enter the client name";
gets(P->Cname);
P->Next=NULL;
if(front==NULL && rear==NULL)
{ front=P;
rear=P;
}
else
{ rear->Next=P; rear=P; } }
Ans 90.
void DELETE()
{ Node *temp;
if(front==NULL) // No element in
the queue
{ cout<<”UNDERFLOW………………..”;
}
else
{ temp=front;
front=front->Link;// Making the second node as the
first one
temp->Link = NULL;
delete temp; // deleting the previous first
node.
}
}