problem in insert function singly linked list

hello :)

can any one tell is there any problem in the following code


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void LED::insert(char elm[],int SIZE)
{
	nodeptr add=NULL;
	nodeptr newptr=new nodetype;;
	//nodeptr addc;
	for(int i=0;i<SIZE;i++)
	{
		newptr->data[i]=elm[i];
	}
	newptr->link=NULL;
	if(add==NULL)
	{
	head=newptr;
	add=newptr;
	}
	else
	{
		add->link=newptr;
		add=newptr;
	}

	add->link=NULL;
}


if i insert a sequence of :
11111111111
22222222222

and print the list will out put the last node:
2222222222222222

There is a small problem with it.

Every insert call results in head being set to the new node, and all other nodes owned by the list being discarded (resulting in a memory leak.)
can u explain
i didn't get it :0
Last edited on
This may work a little better:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void LED::insert(char elm[],int SIZE)
{
	nodeptr newptr=new nodetype;
	
	for(int i=0;i<SIZE;i++)
	{
		newptr->data[i]=elm[i];
	}
	
	if(head==NULL)
	{
	    head=newptr;
	    newptr->link=NULL;
	}
	else
	{
	    newptr->link=head;
	    head=newptr;
	}
}

Hopefully the rest is OK.
it's work
but i want to add from the begging

look what ur code do

input:
>111111111
>222222
>33333
>44444
>5555555
//
DONE INSERTION
5555555
44444
33333
222222
111111111


i want output be like :
111111111
222222
33333
44444
5555555
Yes, its supposed to work that way.

How about this?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void LED::insert(char elm[],int SIZE)
{
	nodeptr newptr=new nodetype;
        newptr->link=NULL;
	
	for(int i=0;i<SIZE;i++)
	{
		newptr->data[i]=elm[i];
	}
	
	if(head==NULL)
	{
	    head=newptr;	    
	}
	else
	{
            nodeptr iter = head;
            while( iter->link ) iter = iter->link;
	    iter->link=newptr;
	}
}
thaaaaaaaaaaaaaanks :)

it's work

god bless u :)
Topic archived. No new replies allowed.