﻿ VB.NET exercises and solutions: delete elements of linked list

# VB.NET exercises and solutions: delete elements of linked list

### Delete elements of singly linked list

Step 4: Delete an element of the singly linked list

To delete an element of the linked list, you need to consider the followings:

1. If the element to be deleted is the first element of the list and the list contains only one element, you only need to assign Nothing to the pfirst and plast. If the element to be deleted is the first element of the list and the list contain more than one element, you need a temporary variable to point to the pfirst then move the pfirst to point to its next element and set the temporary variable to Nothing.

2. If the element to be deleted is in the middle of the list, you need a traversing variable(temp) to point to the element before the element to be deleted and a temporary variable(del) to point to the element to be deleted. Then let the link of the traversing pointer to point to the link of the temporary pointer. To handle situation where the element to be deleted is the last element of the list, you need to test whether the link of the temporary variable is Nothing. If it is really Nothing, you need to update the plast pointer to point to the traversing variable. Finally set the temporary pointer to Nothing.

VB.NET code to delete an item from the linked list:
Public Overrides Sub delete(ByVal pos As Integer)

If (countitem() > 0) Then
'make sure the list is not empty.
Dim temp, del As ListNode

If (pos = 1) Then
'delete the first item
If (countitem() = 1) Then 'The list contains only one item
pfirst = Nothing
plast = Nothing

Else 'The list contains more than one item
temp = pfirst
pfirst = pfirst.nextlk
temp = Nothing

Console.WriteLine("Deleted")

End If

ElseIf (pos > 1 And pos <= countitem()) Then
'delete middle item
temp = pfirst
Dim i As Integer
For i = 1 To pos - 1
temp = temp.nextlk 'move to the item staying before the target item to be deleted

Next
del = temp.nextlk 'target item to be deleted
temp.nextlk = del.nextlk
If (IsDBNull(del.nextlk)) Then
plast = temp 'delete last item
del = Nothing
Console.WriteLine("Deleted")
End If
Else : Console.WriteLine("Invalid position!")
End If

Else : Console.WriteLine("No item found")
End If

End Sub