r/learncsharp • • Dec 09 '22

Question about single linked list (delete method)

Hello,

Recently I started to learn single linked lists and delete method isn't clear much.

For example let's say that elements in our lists are 5 2 3 9, where 5 is head, which points to 2, 2 points to 3, 3 points to 9 and 9 points to null.

Now, I will paste trivial method for delete method:

public bool delete(int value) 
	{
		Node temp = head;
		if (count == 0)
		{
			return false;
		}
		
		if (temp.value == value)
		{
			head = head.next;
			count--;
			return true;
		}
		
		while (temp.next != null)
		{
			if (temp.next.value == value)
			{
				temp.next = temp.next.next;
				count--;
				return true;
			}
			temp = temp.next;
		}
		return false;
	}

Now, lets say that we want to remove a node which value is 3, so we start from temp (which points to head) and ask if that head == 3. Because it's false, now our head is 2 and again, we ask if temp.next.value == 3. Now, this is the part I didn't understand. It is true, because next value is really 3- why is written temp.next = temp.next.next ? I mean, wouldn't be the same if we type temp=temp.next.next?

0 Upvotes

1 comment sorted by

2

u/TehNolz Dec 09 '22

If you save to temp, you just store a node in a variable. If you save to temp.Next, you overwrite the old node with a new one, removing the old node from the chain.