COMPUTER SCIENCE LINKED LISTS , STACKS AND QUEUES

3.e) Each node of a STACK contains the following information, in addition to pointer field:

(i).Pin code of city
(ii).Name of city

Give the structure of node for the linked STACK in question. TOP is a pointer that points to the topmost node of the STACK. Write the following functions:

a) PUSH( ) – To push a node into the STACK, which is allocated dynamically.
b) POP( ) – To remove a node from the STACK, and release the memory.

4

Solution:

struct City
{ long Cpin ;
char CName[20] ;
City *Next ;
} ;
class Stack
{ City *Top;
public:
Stack( ) { Top = NULL; }
void Push( );
void Pop( );
void Display( );
};
void Stack::PUSH( )
{ City *Temp;
Temp=new City;
if(Temp= =NULL)
{
cout<<”\nNo memory to create the node…”;
exit(1);
}
cout<<”\nEnter the City Pin Code to be inserted: “;
cin>>Temp → Cpin;
cout<<”\nEnter the City Name to be inserted: “;
gets(Temp → CName);
Temp → Next=Top;
Top=Temp;
}
void Stack::POP( )
{ City *Temp;
if( Top= = NULL)
cout<<”Stack Underflow…”;
else
{ cout<<”\nThe City Pin Code for the element to delete: “<<Top→Cpin;
cout<<”\nThe City name of the element to delete: “<<Top→CName;
Temp=Top;
Top=Top → Next;
Delete Temp;
}
}

 

CBSE Computer Science Solved Revision Tour By Mr. Ravi Kiran ( [email protected] )