Tuesday, March 30, 2010

Bag Datastructure

An unordered collection of values that may have duplicates.

A bag has a single query function, numberIn(v), which tells how many copies of an element are in the bag, and two modifier functions, add(v) and remove(v).

numberIn(v) = returns no of element in Bag of type v;
add(v) = add a new element v in the bag;
remove(v) = removes all the element from the Bag of type v;
showBag() = prints all the element of the Bag;

Implementation of Bag in cpp(template).

#include < iostream >
#include < string.h >

using namespace std;

template < class Data >

class Bag
{
private:
struct node
{
Data data;
node *link;
}*ptr;
public:
Bag()
{
ptr = NULL;
}

void add(Data a)
{
if(ptr==NULL)
{
ptr = new node;
ptr- > data = a;
ptr- > link = NULL;
}
else
{
node *temp;
temp = new node;
temp- > data = a;
temp- > link = ptr;
ptr = temp;
}
}

void remove(Data data){
int present = 0;
if(ptr==NULL){
cout < < "Error !! Bag is empty" < < endl;
return;
}
else{
node *temp;
node *preTemp;
temp = ptr;
while(temp != NULL){
if(temp- > data == data){
if(temp == ptr){
ptr = ptr- > link;
delete temp;
temp = ptr;
}
else if(temp- > link!=NULL){
preTemp- > link = temp- > link;
delete temp;
temp = preTemp;
}
else if(temp- > link==NULL){
preTemp- > link = NULL;
delete temp;
}
}
else{
preTemp = temp;
temp = temp- > link;
}
}
}
}

int numberIn(Data data){
int count = 0;
if(ptr==NULL)
{
return count;
}
else
{
node *temp;
temp = ptr;
while(temp != NULL){
if(temp- > data == data){
count++;
}
temp = temp- > link;
}
}
return count;
}
void showBag(){
node *temp;
temp = ptr;
while(temp!=NULL){
cout < < " [" < < temp- > data < < "] " < < endl;
temp = temp- > link;
}
}
};



int main()
{
int input,remove;
Bag < int > intBag;

for(int i=0;i < 20;i++)
{
cin > > input;
intBag.add(input);
}
intBag.showBag();
cin > > remove;
cout < < "NumberIN = " < < intBag.numberIn(1) < < endl;
intBag.remove(remove);
cout < < "removed" < < endl;
intBag.showBag();
}

No comments:

Post a Comment

Search Ranjeet's Blog