Delete 1st node in a linked list

Hello, I'm relatively new to C++ and I'm writing a program that includes a delete function which will allow the user to delete any node by selecting the student ID. The function does delete any node in the middle and the last node, but whenever I delete the 1st, I get an error message. Here's the function code:

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
void delete(student *head){
     student *currptr, *nnptr, *delptr;
     int sid;
     
     cout << "Enter the Student ID that you would like to delete: ";
     cin >> sid;
     cout << endl;
     
     currptr = head;
     delptr = currptr -> link;
     
     while(delptr -> sid != sid){
                   currptr = currptr -> link;
                   delptr = delptr -> link;
                   }//end of while statement
     
     if(currptr == head){
                delptr = currptr;
                head = head -> link;
                delete delptr;
                }//end of if statement (DOES NOT DELETE 1ST NODE)
     else{
          currptr -> link = currptr -> link -> link;
          delete delptr;
          }//end of else statement
          
     delptr = NULL;
     currptr = NULL;
     }//end of deletefn 

I really have tried everything I could think of and I seem to have exhausted my resources. Posting in a forum is my last option, so any help would be appreciated. Thanks!
Last edited on
Ok, first of all, don't name your function delete.

Your code DOES delete the first node, it's just that the caller of the function never notices it because the caller passes in a COPY of the head pointer. The head pointer that the caller has does not change.

Okay, are you saying that I should be passing *head by reference? I'm not sure I 100% understood what you were saying. Thanks!
Last edited on
Yes, exactly.
I'm now passing *head by reference, but unfortunately my program is still freezing whenever I attempt to delete the 1st node. I can't figure out what I'm missing. Again, thanks.
Can you post more of your code?
Probably a dumb question, but just to be sure. You are creating ALL of your list dynamically right? You don't have one statically declared and then you add the others dynamically do you?
Topic archived. No new replies allowed.