I have started learning C++ and as a first project, I am trying to make a linked list application. I have not had any real problems with the linked list concept so far as I have previously worked with it in a different language.
So far, I already have working functions to add items to the list and to print it. In the main() class, I can add items one by one, but when I try to add multiple items via a for or while loop.
I have separate functions to create an item and to add it to (the beginning of) the list:
ListItem createItem(int value)
{
ListItem x;
std::cout << &x;
x.value = value;
return x;
}
void addBeg(ListItem* &start, ListItem &item)
{
// Adding to an empty list
if (start == nullptr)
{
item.prev = &item;
item.next = &item;
}
else
{
std::cout << std::endl <<"X" &item;
item.prev = (*start).prev;
(*item.prev).next = &item;
item.next = start;
(*start).prev = &item;
}
start = &item;
}
My main() function looks like this:
int main(void)
{
using namespace std;
// List is empty at the beginning.
ListItem* start = nullptr;
printList(start);
// This doesn't work:
int i = 0;
while (i < 10)
{
ListItem a = createItem(i);
addBeg(start, a);
i++;
}
// This works:
addBeg(start, createItem(12));
addBeg(start, createItem(13));
addBeg(start, createItem(-42));
addBeg(start, createItem(1));
addBeg(start, createItem(-85));
printList(start);
return 0;
}
I cannot seem to graps why it doesn't work. One reason I have thought of is that ListItem a does not reset in each iteration, but that does not make any sense whatsoever to me. Any help or idea is appreciated.