I created a LinkedList
class with a function delete
to remove a certain node from the list if found, however it's not working:
public class LinkedList
{
public Node head;
<...>
public void delete(string n)
{
Node x = search(n); //returns the node to delete or null if not found
if (x != null)
x = x.next;
}
<...>
}
I figured all I needed to do is find the node and set it to the next one (so the node is "removed" out of the linked list), however it's not. If anyone could help me out it'd be much appreciated!
EDIT: Forgot to mention I have a single linked list.
EDIT2: My new code:
public void delete(string n)
{
Node x = head;
while (x != null && x.name != n)
{
if (x.next.name == n)
x.next = x.next.next;
x = x.next;
}
if (x != null)
x = null;
}
You'll want to loop through the list until the next node is the one you want to delete. Then set the current to the next nodes next node.
This of course assumes you only want to delete the first match.