Reputation: 120
So i've been trying to code a linked list. When i debug or if i put one more print statement like this;
intlist.add_node(7);
intlist.print_list();
intlist.add_node(8);
It works fine prints;
5
7
5
7
8
But if i remove that statement, it only prints three eights. Same goes for debugging, it seems working but if i just run it doesn't. I didn't understand what is wrong. Here's my main;
int main(){
Linked_list intlist;
intlist.add_node(5);
intlist.add_node(7);
intlist.print_list();
intlist.add_node(8);
intlist.print_list();
return 0;
}
header;
class Linked_list{
public:
Linked_list();
void add_node(int data);
void remove_node(int data);
int get_data(int index);
void print_list();
struct Node {
int data;
Node* next;
};
Node* head;
int lenght;
};
And header's source file;
Linked_list::Linked_list(){
head = 0;
lenght = 0;
}
void Linked_list::add_node(int data){
Node* newnode = new Node;
newnode->data = data;
newnode->next = NULL;
if (head == 0) {head = newnode; lenght = 1; return;}
else{
Node* temp = new Node;
temp = head;
while (temp->next != NULL){
temp = temp->next;
}
lenght++;
temp->next = newnode;
delete temp;
}
}
void Linked_list::remove_node(int data){
return;
}
int Linked_list::get_data(int index){
return 0;
}
void Linked_list::print_list(){
if (head == 0) {std::cout << "List is empty!!" << std::endl;
return;}
else{
Node* ptr = new Node;
ptr = head;
for (int i = lenght; i > 0; i--){
std::cout << ptr->data << std::endl;
ptr = ptr->next;
}
}
}
Upvotes: 2
Views: 55
Reputation: 326
Your add_node function should be:
void Linked_list::add_node(int data) {
Node* newnode = new Node;
newnode->data = data;
newnode->next = NULL;
if (head == 0) {
head = newnode;
lenght = 1;
return;
} else {
//Node* temp = new Node;
Node *temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
lenght++;
temp->next = newnode;
//delete temp;
}
}
You don't need to create a new Node
object since you are only looking to reference head. delete temp
actually deletes the content of the address previously pointed to by temp
, which is the last element of your list.
Upvotes: 4