Linked lists

Hello,

I am new to C++ programming. I have started learning by myself a couple of weeks ago. I have written the following program for generating linked lists but i am getting an error i dont understand. Can you please have a look at it?

#include<stdlib.h>
#include<stdio.h>
#include <iostream>
using namespace std;


struct node
{ char name[20];
node *nxt; // Pointer to next node
};


node add_node (node * x)
{


x = new node;
cout << "Please enter the name of the person: ";
cin >> x->name;
x->nxt = NULL;
return * x;


}


int main() {
node * head, * current;
int i;

head = NULL;

i = 0;
while (i < 5){
* current = add_node(current);

if (head == NULL){
head = current;
}
current = current->nxt;
i = i + 1;
}
return 0;
}


thanks!
The problem is in function add_node.
x is just a copy of current, so new changes the value of x but not the value of current. You can either make x a node** (then there is no point in returning anything), or make add_node return a node* (then it won't need any parameters).

Hope this helps.

By the way, next time use code tags and say what was the error message.
Last edited on
Thanks for the reply but i still dont get it. I tried something else now but it doesnt work. I dont get an error message but I think i only create the first node of the list and nothing else. Thanks again!

#include<stdlib.h>
#include<stdio.h>
#include <iostream>
using namespace std;


struct node
{ char name[20];
node *nxt; // Pointer to next node
};


node add_node (node * x)
{


cout << "Please enter the name of the person: ";
cin >> x->name;
x->nxt = NULL;
return * x;


}

void print_lists(node * head){
while (head != NULL){

cout << head->name;
head = head->nxt;
}
}

int main() {
node * head, * current;
int i;

head = NULL;

i = 0;
while (i < 5){

current = new node;
* current = add_node(current);
if (head == NULL){
head = current;
}
current = current->nxt;
i = i + 1;
}
print_lists(head);
return 0;
}
Very similar problem here as before.
current = current->nxt;
In this line you set current to the value of current->nxt ( which is null ).
current = new node;
In this line you set current to the address of a new node, but that doesn't affect current->nxt.

I suggest you do something like this in the loop:
1
2
3
4
5
6
7
8
9
if(head == NULL){
    head = new node;
    add_node(head);
    current = head;
}else{
    current->nxt = new node;
    add_node(current->nxt);
    current = current->nxt;
}

Here current always points to an existing node, and its value is not affected by new.

Also, in function add_node you already modify the node pointed by x, so there is no point to do so by returning something.
Last edited on
Topic archived. No new replies allowed.