Linked List Insert value problem

Anyone can say, whats wrong here?

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
41
42
43
44
#include <iostream>
using namespace std;
class node{
	public:
	int value;
	node *next;
	void insert_front(node *&head, int y);
};

void insert_front(node *&head, int y)
{
	node *temp;
	temp = new node;
	temp->value = y;
	temp->next = NULL;
	

	if(head == NULL){
		temp->next = NULL;
		head = temp;
	}

	else{	
		temp->next = head;
		head = temp;
	}
}

int main()
{
        
        node *head = NULL;
	int x;
	
        insert_front(head, 2);
	insert_front(head, 3);
	insert_front(head, 4);

	for(node *j=head; j->next!=NULL; j=j->next)
		cout<<j->next->value<<endl;
	
	system ("Pause");
	return 0;
}


The problem is, It doesnt insert the last inserted value; or doesnt display last inserted value.
That is in here, 4 doesnt display in between inserted values 2,3,4(4 is the last inserted value). Or if I insert just 2(2 is last inserted value since its the only inserted value), it doesnt display anything.
Where I made mistake???
1
2
3
4
5
6
7
void insert_front(node *&head, int y)
{
	node *temp(new node);
	temp->value = y;
	temp->next = head;
	head = temp;
}


http://ideone.com/MMcfoB
Last edited on
Ok, I did like you showed here.
The thing is confusing to me, Am I loosing any node without using if/else?

1
2
temp->next = head;
head = temp;
Should my for loop in main() look like this
1
2
for(node *j=head; j!=NULL; j=j->next)
		cout<<j->value<<endl;

instead this?
1
2
for(node *j=head; j->!=NULL; j=j->next)
		cout<<j->next->value<<endl;
The second for-loop is what you should use. Look at the link I had in my answer
Thanks. Worked..
Topic archived. No new replies allowed.