basic linked list program problem

This is a discussion on basic linked list program problem within the C++ Programming forums, part of the General Programming Boards category; I want to create a link list that has two record,
and insert another record in between the two.
However ...

basic linked list program problem

I want to create a link list that has two record,
and insert another record in between the two.
However my program is not working properly in the sense that the linked list did not really re-link after I commanded it to.

I suspect that everyone posting questions about linked lists is a student of some sort, and telling them to use the STL is probably not going to help much. Most instructors won't allow it, and (more importantly) how would they ever learn how it works if they don't code it themselves at least once?

Anyways, to the OP:

Your list structure is correct but here's a few points:

Code:

struct list{
char event[20];
int year;
list *next;
};
list *head = NULL; // the head of an empty list
void insert(list*, char incident[20], int);
int main()
{
// This is how you make a new node in the list:
head = new list;
strncpy(list->event, "World War II", 20);
list->year = 1914;
list->next = NULL; // remember to mark the end of the list
return 0;
}

I suspect that everyone posting questions about linked lists is a student of some sort, and telling them to use the STL is probably not going to help much. Most instructors won't allow it, and (more importantly) how would they ever learn how it works if they don't code it themselves at least once?

My response was to his question about making his program shorter, which I showed him how to do, using the STL. If there are specific requirements per his homework then he should post them; I am not responsible for his homework.

Originally Posted by MacNilly

Anyways, to the OP:

Your list structure is correct but here's a few points:

Code:

struct list{
char event[20];
int year;
list *next;
};
list *head = NULL; // the head of an empty list
void insert(list*, char incident[20], int);
int main()
{
// This is how you make a new node in the list:
head = new list;
strncpy(list->event, "World War II", 20);
list->year = 1914;
list->next = NULL; // remember to mark the end of the list
return 0;
}

1. Using global variables is a bad practice and not required for this problem. The anchor of the linked list should be within main.
2. It is not ok to use char arrays vice std::strings in C++, this is extremely poor practice and should never be suggested.
3. In order to make a new node, he should use a function, but not one that you have suggested since your function is broke.

Honestly, it would have been much easier to just rework my example without the STL list container if that is what you are so concerned with. For the future if you are going to correct someone, ensure you are in fact correct.