incomplete program- help needed with insertbeg() function

closed account (1vf9z8AR)
I am doing linked lists and want to enter new values to beginning of my list.
Can't figure out what to do in insertbeg(int x) 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
  #include<iostream>
using namespace std;
struct node
{
   int data;
   node* next;     
};
node* start;
void insertbeg(int x)
{
        node* temp=x;
        x=start;
        start=temp;
}
int main()
{
        int x;
        char ch;
        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();
}
You need to create a new node.
Line 11: You're trying to assign an int to a node pointer.
Line 12: You're trying to assign a node pointer to an int passed by value.
1
2
3
4
5
6
7
8
node* start = nullptr;    // Globals are initialized to null by default, but good style to explicitly initialize.

void insertbeg(int x)
{   node * temp = new node;        //  Need to allocate a new instance
     temp->data = x;         //  Assign the data 
    temp->next = start;     //  Assign the link to the current start of the list
    start = temp;           //  Assign this node to the new front of the list
}


closed account (1vf9z8AR)
It works now but i cant understand what is happening at each step.
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();
}
I gave you comments explaining each line of my insertbeg().

Regarding display:
Line 18: Create a pointer (uninitialized) called np.
Line 19: Assign the np pointer to the first node (if any). If the list is empty, start and np will be null.
Line 20: Loop while np is pointing to a valid node. When the end of list is reached, np is null and the loop exits.
Line 21: cout the value of the data stored in the node.
Line 22: Update np to point to the next node (if any).


Topic archived. No new replies allowed.