linked lists problem2

Hey i write this function to add at the last of the link list
but when a display them the first node is displayed , someone help me plz.

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
45
46
47
48
 #include<iostream>
using namespace std;
struct node{
	int data;
	node *next;
};


void add(node **head)
{
	int x;
	cin>>x;
	node *ptr,*loc;
	ptr=new node;
	ptr->data=x;
	ptr->next=NULL;
	if(*head==NULL)
	{
		*head=ptr;
		
	}
	else
	{
		loc=*head;
		while(loc->next!=NULL)
		{
			loc=loc->next;
			loc->next=ptr;
		}
	
		
		 
	}
}
int main()
{
	node *head=NULL;
	for(int i=0;i<5;i++)
		add(&head);

	for(node *loc=head;loc!=NULL;loc=loc->next)
		cout<<loc->data<<" ";



	system("pause");
	return 0;
}
Last edited on
Youn add function sets new node as next for all nodes (wrecking list structure and leaking memory)
i don't understand you?
A diagram of what is happening: http://imgur.com/2ih5ASq
Topic archived. No new replies allowed.