I'm struggling with the addAtHead(val:Int) implementation in designing my own linked list.
I realise that I need to assign self.next to the current object, but because the boilerplate code is a Class and not a struct, it's a reference type, so I end up with a neverending recursion if I do this:
func addAtHead(_ val: Int) {
self.next = self
self.val = val
}I've tried initialising a new next instance, but then I can't do self = next because I can't mutate self.
I know that I could fix this by using a struct or by possibly creating a copy method, or having a head property, but it feels like the way that the problem is written it should be achievable in a few lines.
Any suggestions? I've got all the other functions sorted.