Amit
asked on
setting value to a pointer of a linklist
I have made the following linklist. How can I create a loop
say for example if I want to set first->next->next=somethin g;
then I want to set first->next->next->next=so mething;
I hope I am clear enough, what I need to do is replace ->next .. by a loop so if need 3 ->next I just run a for loop 3 times. I am doing it because I need to add a node at the nth position of my list; If the list already has some elements. For example the function addnth which I have tried to implement. The function is generic to add a node at the 2nd position from head. But I need it to be versatile enough to add at any location. However I am unable to do that because of difficulty in moving to first->next.....I even tried using pointer to pointer but was unable to do that.
__________________________ __________ ___
struct node
{
int x;
node *next;
};
class linklist
{
node *first;
int length;
public:
linklist()
{
first= NULL;
length=0;
}
void addlink(int d);
void display();
void addnth(int d,int n);
};
void linklist::addnth(int d,int n)
{
node *current=first;
node *temp=0;
node **temp1=0;
node *m=0;
for (int i=1;i<3;i++)
{
current=current->next;
}
temp=current;
node *newlink=new node;
newlink->x=d;
first->next->next=newlink;
/*
m=first->next->next;
temp1=&m;
*temp1=newlink;
*/
newlink->next=temp;
}
say for example if I want to set first->next->next=somethin
then I want to set first->next->next->next=so
I hope I am clear enough, what I need to do is replace ->next .. by a loop so if need 3 ->next I just run a for loop 3 times. I am doing it because I need to add a node at the nth position of my list; If the list already has some elements. For example the function addnth which I have tried to implement. The function is generic to add a node at the 2nd position from head. But I need it to be versatile enough to add at any location. However I am unable to do that because of difficulty in moving to first->next.....I even tried using pointer to pointer but was unable to do that.
__________________________
struct node
{
int x;
node *next;
};
class linklist
{
node *first;
int length;
public:
linklist()
{
first= NULL;
length=0;
}
void addlink(int d);
void display();
void addnth(int d,int n);
};
void linklist::addnth(int d,int n)
{
node *current=first;
node *temp=0;
node **temp1=0;
node *m=0;
for (int i=1;i<3;i++)
{
current=current->next;
}
temp=current;
node *newlink=new node;
newlink->x=d;
first->next->next=newlink;
/*
m=first->next->next;
temp1=&m;
*temp1=newlink;
*/
newlink->next=temp;
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Sorry, I can not undestand why do you want to use pointer to pointer.
I doesn't make much sense to me.
I doesn't make much sense to me.
ASKER
-regards