Showing posts with label Data Structures codes. Show all posts
Showing posts with label Data Structures codes. Show all posts

Sunday, November 16, 2008

Node.h (data structures)

#include "Node.h"

int main()
{
Node n;
int choice=0;
int val=0;

while(choice!=5)
{
cout<<"\n1.Enter new item";
cout<<"\n2.Remove item";
cout<<"\n3.Dislplay list";
cout<<"\n4.Get item count";
cout<<"\n5.Exit";
cout<<"\nChoice:";
cin>>choice;

switch(choice)
{
case 1:
cout<<"\nEnter Value of new item:";
cin>>val;
n.setData(val);
n.displayItems();
break;

case 2:
cout<<"\nEnter value of item:";
cin>>val;
n.removeNode(val);
n.displayItems();
break;

case 3:
n.displayItems();
break;

case 4:
cout<<"\nNode count:"< break;

case 5:
return 0;
default:
cout<<"\nWrong choice:";
}
}
return 0;
}


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;
}
;