Hello!
I made a simple program to practice linked list basics with the current goal being to be able to insert a new node in front of head or before head if i choose to do so.
the problem is that the last 2 inserts show that the data is 0 and the first insert shows as if it was the last one with the correct data.
Program output:
Data at location 0 is: 0 //<--the reason behind this one is the constructor(not a problem)
Data at location 1 is: 0
data at location 2 is: 0
data at location 3 is: 51
I suspect the printList function but cant pinpoint where the problem occurs.
Any help will be much appreciated.
when you insert into a singly linked list you'd have to check first whether or not the list is empty node *temp; - a data-member is usually a representation of some characteristics for the datatype (e.g class Person would have name, age, etc as data-members). so a full-fledged data-member of the list is not necessary just to iterate through the list, you can declare local variables for that purpose
in front: ... head: new node
1 2 3 4 5 6 7 8 9 10 11 12 13
void insertAfterHead(constint& data)
{
node* temp = new node(data);
if(head)
{
temp -> next = head -> next;//head assigns ownership of it's next to temp
head -> next = temp;//then head's next is reassigned to temp
}
else //list is empty so temp becomes head;
{
head = temp;
}
}
before: ... newNode : head:
1 2 3 4 5 6 7 8 9
void insertBeforeHead(constint& data)//const qualify data
{
node* temp = new node(data);//overloaded ctor
if(head)//if list is not empty
{
temp -> next = head;
}
head = temp;
}
your list also needs a destructor as the objects allocated with new are not automatically released
finally, this link has a discussion on singly linked lists with a working print()/display() method: http://www.cplusplus.com/forum/beginner/210637/
when you insert into a singly linked list you'd have to check first whether or not the list is empty
node *temp; - a data-member is usually a representation of some characteristics for the datatype (e.g class Person would have name, age, etc as data-members). so a full-fledged data-member of the list is not necessary just to iterate through the list, you can declare local variables for that purpose
I understand your solution but i still cant understand why mine doesn't work. I know my way is far from perfect but my goal was to learn only the logic behind the list and try to build it myself before i watch a proper guide on how to make one.
your list also needs a destructor as the objects allocated with new are not automatically released
I know that they don't release automatically and i did make a destructor:
1 2 3 4 5 6 7 8 9
list::~list() {
node* prev = head;
node* pnext = head;
while (pnext) {
prev = pnext;
pnext = prev->next;
if (pnext) delete prev;
}//while end
}//destructor end
Though i don't know if it is supost to be done that way