Trying to built linked list...need help!

I am trying to build a linked list but I keep having trouble with it!!
Please correct my code!!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include "linked_list.h"

using std::cout;

node::node(){
	head = NULL;
	next = NULL;
	data = 0;
}


node::~node(){

	for(node* current = head; current != NULL; current = current->next){
		delete current;
	}
}
void node::insert(int value){
	if(head == NULL){
		node* ptr = new node();
		head = ptr;
		ptr->data = value;
		head->next = NULL;
	}
	else{
		node* ptr = new node();
		next = ptr;
		ptr->data = value;
		ptr->next = NULL;
	}

}
void node::show(){
	for(node* current = head; current != NULL; current = current->next){
		cout<<current->data<<"\t";
	}
}



There is a header file called linked_list.h!!!
http://www.cplusplus.com/forum/articles/40071/#msg218019

1
2
3
for(node* current = head; current != NULL; current = current->next){
	delete current;
}
You are trying to access the object that just got destroyed.


┬┐what are you trying to do in line 28?
Can you please include the header file as well so we can see the structure of the list and nodes.
You don't want to delete the whole list in the node's destructor, else you can't remove a node.

1
2
3
4
5
6
7
struct node
{
 int data;
 node*next;

 node(int d, node* n) :data(d), next(n) {}
];




List's that have a "push_back" function typically have a "tail" as well as head:
1
2
3
4
5
6
if (!head)
 head = new node(value, NULL);
else if (!tail)
 tail = head->next = new node(value, NULL);
else
 tail = tail->next = new node(value, NULL);


For beginning, "push_front" is easier:
head = new node(value, head);
Last edited on
> You don't want to delete the whole list in the node's destructor, else you can't remove a node.
You can, you just need to `unlink' it first.
But it's a good catch, you are also causing an stack overflow


If you use a header cell (instead of a pointer) `push_back()' simplifies
1
2
3
4
5
6
7
8
9
10
void list::push_back(const T &item){
   last->next = new node(item, &head); //circular
   last = last->next;
}

list::list(),
   last(&head)
{
   head.next = &head; //circular
}
Last edited on
Topic archived. No new replies allowed.