Linked Lists

Ok so i'm trying to write a function that will delete the first node in the linked list and headptr will point at the new first node, but i keep hitting segfaults. here is my most recent attempt at it. the list is already defined too in main.


1
2
3
4
5
6
7
8
9
void DeleteFirst(Node*& headptr)
{
   Node* prevptr;
   headptr = prevptr;
   prevptr -> next;
   delete prevptr ->next;
   prevptr -> next;
   delete prevptr;
}
Line 4: The assignment appears to be backwards.
Lines 5 and 7: These do nothing.
This should do:
1
2
3
4
5
6
7
8
9
void DeleteFirst(Node*& headptr)
{
   // save pointer to first node for deletion.
   Node* prevptr = headptr;
   // advance the headptr
   headptr = prevptr -> next;
   // now delete the prevptr
   delete prevptr;
}

Why not use the list from the standard template library. See "http://www.cplusplus.com/reference/stl/list/".
@Ralph83

Some people like to write their own code and understand it, rather than just use somebody else's code...
@ helios
thanks for the help! sorry to get back late but it did work once i flipped around line 4 and tweaked 5 and 7.
@Ralph83
it was part of a programming assignment using the professor's own setup for it, otherwise i would have in a heartbeat if i could have. and I appreciate the code but packetpirate is right, I would much rather understand the code than just copy it, but seeing how it works helps it sink in also!
Topic archived. No new replies allowed.