Followers 0

## 2 posts in this topic

I  currently trying to modifying this code so it will adding new data from behind but it seems that I can only code it in front of the previous data.
I can't see what's wrong with it. Does it have to do with printitem() function? Here's my header. Hope that someone will help me since I'm a bit lost.
#ifndef list_h
#define list_h
template<class t>
class list
{
private:
class node
{
public:
t data;
node*next;
};
node*current;
int numitem;
public:
list();
~list();
bool traverse(t,int&);
void printdata();
int numberofitem();
};
template<class t>
list<t>::list()
{
numitem=0;
};
template<class t>
list<t>::~list(){};
template<class t>
{
t item;
node*newnode=new node;
cout<<"enter data: ";
cin>>item;
newnode->data=item;
numitem++;
};
template<class t>
void list<t>::printdata()
{
while(current !=0)
{
cout<<current->data<<" ";
current=current->next;
}
cout<<endl;
};
template<class t>
int list<t>::numberofitem()
{
return numitem;
};
template<class t>
{
t item;
t node_number;
cout<<"enter the item location: ";
cin>>node_number;
node*temp1;
temp1=(node*)malloc(sizeof(node));
for(int i=1;i<node_number;i++)
{
temp1->next;
if(temp1==NULL)
{
cout<<node_number<<" location is not exist"<<endl;
break;
}
}
cout<<"enter new item: ";
cin>>item;
node *temp;
temp=(node*)malloc(sizeof(node));
temp->data=item;
temp->next=temp1->next;
temp1->next=temp;
};
template<class t>
bool list<t>::traverse(t target,int &loc)
{
if(numitem==0)
{
cout<<"there is no item in the list. "<<endl;
}
else
{
loc=0;
while(current->data !=target&& current->next !=0)
{
current=current->next;
++loc;
}
if(current->data==target)
return true;
else
return false;
}
};
#endif
Edited by Hodgman
0

##### Share on other sites

I haven't read your code exhaustively in that regard, but are you saying that you can only add items to the front of the list?  That seems to be the behavior you're after in the first place, since you've only got methods to add to the front and middle.

If you want to add to the rear, I'd suggest having a tail pointer as well as a head.

0

##### Share on other sites

You obviously didn't write this thing yourself, and it looks like you are asking us to complete your school work for you.

For starters, there is a function called addtofront() and addinmiddle() which both asks for user input for some reason, instead of taking in these values as function parameters.

Second, you will need a new function, which we could call addtoback()

To add something to the back of a linked list (- this variation being one of the most useless structures in existence,) traverse the entire thing to the last end, and have its next pointer point to a new node that you just "added" with addtoback()

Typically, when you want to add something to a structure, you would want something to add, from somewhere, say, from the parameter list of a function:

template<class t>

1

## Create an account

Register a new account