Here are the subroutines I'd use for adding and removing objects to/from linked lists:
Code:
;X: index of the current item;
;FirstItem: index of the first item in the linked list;
AddItem:
lda FirstItem ;get the index of the current first item
sta NextItem, x ;have the new item point to it
stx FirstItem ;make the current item the first one
rts ;return
Code:
;X: index of the current item;
;FirstItem: index of the first item in the linked list;
;PreviousItem: index of the previously processed item that WASN'T REMOVED from the list;
RemoveItem:
lda NextItem, x ;get the index of the next item
ldx PreviousItem ;get the index of the item that pointed to this one
bmi :+ ;skip if this is the first item
sta NextItem, x ;make the previous item point to the next item
rts ;return
: sta FirstItem ;make the next item the first
rts ;return
If there are multiple linked lists (i.e. separate groups of objects), index register Y can be used to access a "FirstObjects" array, instead of the "FirstItem" variable.
I really don't mind that
bmi handling the special case of the first item, as it just costs very little CPU time and the code is still pretty clear and easy to follow, but if "tricking the engine" and eliminating the special case doesn't have any drawbacks, then that's fine too.