insert a node at the start of the list

i'm having trouble on how can i insert a node at the start of the list. i figured out on how can i insert a node at the start of the list if it's empty but i don't know how can i insert a node at the start of the list if the start_ptr != NULL.

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
void add_start()
{
     node *temp;
     temp = new node;
     
     cout << "Please enter employee number: ";
     cin >> temp->empnum;
     cout << "Please enter employee first name: ";
     cin >> temp->empfname;
     cout << "Please enter employee last name: ";
     cin >> temp->emplname;
     cout << "Please enter employee salary: ";
     cin >> temp->salary;
     
     temp->nxt = NULL;
     
     if (start_ptr == NULL)
       { 
           start_ptr = temp;
           current = start_ptr;
       }
     else
       { 
           // i don't know.
       }
}

thanks!
1
2
3
4
5
6
7
8
if(start_ptr == 0){
    //temp will be the only node in the list. It will be both first and last, therefore
    temp->next = 0;
}else{
    //there are more nodes, so temp->next will have to lead to them
    temp->next = start_ptr;
}
start_ptr = temp;//needed in both cases 
thanks!^^
@ hamsterman: isn't that a little redundant? Why do you need the if/else at all?

1
2
tmp->next = start_ptr;  // if start_ptr is null, this has the desired effect as well
start_ptr = tmp;
Topic archived. No new replies allowed.