linked list insertion at end

closed account (1vf9z8AR)
Help i am almost close to getting a perfect output.Want to insert new values at end of my 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
  #include<iostream>
using namespace std;
struct node
{
        int data;
        node* next;
};
node* rear;
void insertend(int x)
{
        node* temp=new node;
        temp->data=x;
        temp->next=NULL;
}
void display()
{
        node* np;
        while(np!=NULL)
                cout<<np->data<<"\t";
        np=np->next;
}
int main()
{
        int data;
        char ch;
        rear=NULL;
        do
        {
                cout<<"Enter your data:";cin>>data;
                cout<<endl;
                insertend(data);
                cout<<"Do you want to continue?(y/n)";cin>>ch;
                cout<<endl;
        }while(ch=='y');
        cout<<"Your list-"<<endl;
display();
return 0;
}
Maybe you could explain or show an example.
In a standard linked list the end of the list is the node where the next pointer is NULL. To add at the end, simply move through your next until it equals NULL, change the next pointer to your new node, and set the next pointer of the new node to NULL.
Line 8: rear is wrong. You still need a pointer to the front of the list (start).

Line 11: You need to walk the list to find the last entry in the list.

Topic archived. No new replies allowed.