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


Singly 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.

Delete the first item of the list  

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.

Delete middle item of the list  

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



Comments





This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.