program stops working

closed account (1vf9z8AR)
please keep along the lines of my program.

Program is for insertion at end of linked list.

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
  #include<iostream>
using namespace std;
struct node
{
        int data;
        node *next;
};
node *head=NULL;
void insertend(int data)
{
        node *last=new node;
        last->data=data;
        last->next=NULL;
        if(head==NULL)
        head=last;
        else
        {
                node *temp=new node;
                while(temp->next!=NULL)
                {
                        temp=temp->next;
                }
                temp->next=last;
        }
}
void display()
{
        node *temp=new node;
        while(temp!=NULL)
        {
                cout<<temp->data<<endl;
                temp=temp->next;
        }
}
int main()
{
        int x;
        char ch;
        do
        {
        cout<<"Enter value:";cin>>x;
        cout<<endl;
        insertend(x);
        cout<<"Do you want to continue?(y/n)";cin>>ch;
        cout<<endl;
        }while(ch=='y');
display();
        return 0;
}
Last edited on
closed account (SECMoG1T)
hello: i think your problem occurs when you try to transverse an empty pointer, your temporally pointer should point to the head node of your list

node* temp = head;///then you can transverse your list

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
void insertend(int data)
{
        node *last=new node;
        last->data=data;
        last->next=NULL;

        if(head==NULL)
          head=last;

        else
        {
                //node *temp=new node;//error
                node *temp = head; //correct
                while(temp->next!=NULL)
                {
                        temp=temp->next;
                }
                temp->next=last;
        }
}


void display()
{
        ///node *temp=new node; error
        node *temp = head;//correct
        while(temp!=NULL)
        {
                cout<<temp->data<<endl;
                temp=temp->next;
        }
}
Last edited on
Topic archived. No new replies allowed.