Sunday, November 16, 2008

Node.cpp (data Structures)

#include
#include

using namespace std;

class Node
{
public:
Node()
{
head=NULL;
}
void setData(int val)
{
if(head==NULL)
{
head=new Node;
head->data=val;
head->link=NULL;
}
else
{
Node*temp,*prev;
temp=head;

while(temp->link!=NULL)
{
temp=temp->link;
}
prev=new Node;
prev->data=val;
prev->link=NULL;
temp->link=prev;
}
}
bool removeNode(int val)
{
if(head!=NULL)
{
Node*temp,*rem,*prev;

if(head->data==val)
{
prev=head;
if(head->link!=NULL)
head=head->link;
else
head=NULL;
delete prev;
return true;
}
temp=head->link;
prev=head;
while(temp !=NULL)
{
if(temp->data==val)
{
prev->link=temp->link;
delete temp;
return true;
}
prev=temp;
temp=temp->link;
}
}
return false;
}
void displayItems()
{
if(head !=NULL)
{
Node*temp,*prev;
temp=head;
cout<<"\n"<data<<"->";

while(temp->link !=NULL)
{
temp=temp->link;
cout<data<<"->";
}
cout<<"NULL\n";
}
else cout<<"\nList is empty.";
}

int nodeCount()
{
if(head !=NULL)
{
Node*temp;
temp=head;
int cnt=1;

while(temp->link !=NULL)
{
temp=temp->link;
cnt++;
}
return cnt;
}
else
return 0;
}
private:
int data;
Node*link;
Node*head;
}
;

No comments: