Insertion a new node at the end of LINK LIST

I am working with link list..
i want to add new node after last node..but getting same link list as it is before the calling of
insertion function();
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include<iostream.h>
#include<conio.h>
 struct node
 {
 int info;
 node* nxt;

 };
void trav(node* start);
struct node* insr(node* start,int item);
void main()
{
clrscr();
int n;
node *a,*b,*c,*r;
a=new node;
b=new node;
c=new node;
a->info=444;
a->nxt=b;
b->info=555;
b->nxt=c;
c->info=666;
c->nxt=NULL;
cout<<"link list is as\n";
trav(a);
cout<<"entr a value in link list\n";
cin>>n;
cout<<"list after insertin\n";
r=insr(a,n);// i think here it working wrong 
trav(a);

getch();




}
void trav(node* start)
{
node* ptr;
ptr=start;
while(ptr!=NULL)//????????????
 {
 cout<<ptr->info<<endl;
 ptr=ptr->nxt;
 }

}
struct node* insr(node* start,int item)
{
node* ptr,*cunt;
ptr=new node;
ptr->info=item;
ptr->nxt=NULL;
cunt=start;
if(cunt=NULL)
 {
 start=ptr;
 }
else
 {
  while(cunt->nxt!=NULL)
   { cunt=cunt->nxt;

    }
  cunt->nxt=ptr;


}
return(ptr);
}
closed account (D80DSL3A)
There is one error ( I tested ).
It is on line 57. This error caused the program to crash on my pc.
Can you see why it would cause a crash?

EDIT: The next problem you will find is that you can't insert the 1st node with the insr(). Hint: Line 59 has no effect outside of the function.
Last edited on
Besides some questionable variable name choices?

You don't need to preface your function return type by the type identifier.

 
node* insr(node* start, int item)


You are not attaching the new node to the end of the list. Notice that the condition to terminate the loop is that cunt == NULL, and that you set the value of cunt in the loop, but when cunt is NULL it is essentially detached. At that point you are assigning the ptr to the end of cunt, but its in its own world. Its a memory leak.

try this:
1
2
3
4
5
6
7
8
9
10
11
12

while(cunt->nxt != NULL)
{
if(cunt->nxt == NULL)   //we reached the end!
   {
        cunt->nxt = ptr;
        break;
    }
}

return ptr;
}


don't forget to delete the memory you created.
Topic archived. No new replies allowed.