Deleting in a linked list

Hello, I'm relatively new to C++ and I'm writing a program that is to include a delete function which will allow the user to delete any node in the linked list by inputting the student ID of that particular node. The function does delete any node in the middle and the last node, but whenever I attempt to delete the 1st, the program shuts down. I've got a pretty good understanding of linked lists and how they work, but I can't figure out what I'm missing. Here's the delete 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 deletefn(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;
                   }//while statement scans the list
     
     if(head -> pid == pid_input)//should compare input to head
                delptr = currptr;
                head = head -> link;
                delete delptr;
                }//end of if statement
     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!
Wouldn't it make more sense to compare the head to the input before searching for the value?
The real problem here is that your while doesn't check that delprt is at the end of the list, so last steps go like this:
(delprt==list[n-2])
delprt=delprt->next
(delprt==list[n-1]) (last node)
delprt=delprt->next
(delprt==???) (nowhere)
delprt=delprt->next ("Oops. Dereferencing invalid pointer. Hurk." *dead*)

This will happen whenever sid is not found.
delptr should be initialized to the head, not to head->next. That way you wouldn't need the if, and currptr would be unnecessary.
Wouldn't it make more sense to compare the head to the input before searching for the value?


Helios, you were exactly right! Thank you so much for the insight. After you stare at a program for so long you begin to miss the obvious. Thanks again.
Topic archived. No new replies allowed.