Can someone help me understand what I’m doing wrong. I need to insert a character into a linked list.
It takes an input like a name of person, than it reverses it.
then it tells user to choose a position to add a character.
void insert_char(Node* plist, char x, int p){
Node* d=plist;
for (int i=1; i<p and 0!=d; i++)
d=d->next;
if (0 !=d)
d->x=x;
However, this code changes the character, not adds it.
UPDATE:
I can’t still figure it out.
void insert_char(Node* plist, char x, int p){
Node* d=plist;
Node* d2=0;
for (int i=1; i<p and 0!=d; i++)
d2->next=d->next;
d->next=d2;
if (0 !=d)
d2->x=x;
return;
}
I am getting a segmentation error.
Ok, so i figured out, what i really wanted. Thanks for help
void insert_char(Node* plist, char x, int p){
Node* d=plist;
Node* d2= new Node();
for (int i=1; i<p and d; i++)
d2->next=d->next;
d->next=d2;
if (0 !=d)
d2->x=x;
return;
}
Is overwriting whatever character was there previously. What do you expect to happen?
Can be simplified to just
d, no need to compare to0.It might also be helpful is you use braces. I know it’s nice to be able to ignore them with one lines like this, but it will eventually come back to bite you one day.
As for your update, you’re always going to get a segfault because of these lines:
You’re creating a
Node*and never assigning anything to it, nor allocating memory. You’re dereferencing an uninitialized pointer.Are you sure you’re not trying to do this?