EXplaination of insertbeg and display in layman's language

closed account (1vf9z8AR)
I make this program work using trial and error and from help on this site but i cant understand what is happening at each step in inserbeg(int x) and display() function.Please tell in normal english.

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
  #include<iostream>
using namespace std;
struct node
{
   int data;
   node* next;
};
node* start;
void insertbeg(int x)
{
     node* temp=new node;
     temp->data=x;
     temp->next=start;
     start=temp;
}
void display()
{
        node* np;
        np=start;
        while(np!=NULL)
        {
                cout<<np->data<<'\t';
                np=np->next;
        }
}
int main()
{
        int x;
        char ch;
        start=NULL;
        do
        {
                cout<<"Enter data";cin>>x;
                cout<<endl;
                insertbeg(x);
                cout<<"Do you want to continue?(y/n)";cin>>ch;
                cout<<endl;
        }while(ch=='y');
        cout<<"Your list"<<endl;
        display();
}
Hello suyashsing234,

I am having a hard time trying to explain how this works because it is backwards.

You are putting thee next node in front of the original "start: and changing the address of "start". "start" should be the first node with an address that never changes. Each new node would then come after start so that everything is in the correct order.

The "display" function works, but since the linked list is backwards it prints correctly, but in reverse order from what you entered.

I will work on something that is more of what is generally done that I can explain to you.

In the mean time someone else may say something.

Hope that helps,

Andy
closed account (SECMoG1T)
just adding to what ANDY said.

i got you some useful links check them out.

what does insertbeg do:
-------------------------------
https://stackoverflow.com/questions/19194224/adding-node-to-the-front-of-a-linked-list
http://scanftree.com/Data_Structure/Insertion-in-beg


There's nothing unusual or "backwards" about this implementation (besides the unnecessary use of globals). A singly linked list that inserts at the head is absolutely common. For example, the most basic lists in functional languages such as List and Haskell behave like this.
Last edited on
closed account (1vf9z8AR)
Oh ok guys i think i get a idea about what is happening.

New value gets at the head and start is stored in a temporary value.
After that i am confused.

I even watched this amazing video but still confused.

https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=video&cd=1&cad=rja&uact=8&ved=0ahUKEwjXl_DkuKHXAhUPSI8KHVaPB24QtwIIJTAA&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DcAZ8CyDY56s&usg=AOvVaw1Ti-XVlC0Z_pHTZXrGq-Qs

Anyways i rote learned it.
Topic archived. No new replies allowed.