﻿ VB.NET exercises and solutions: add element to linked list

# VB.NET exercises and solutions: add element to linked list

## Singly linked list

### Add element to singly linked list

Step 2: Add an element to the linked list

To add an element to the linked list, you need to consider 4 things:

1. When the list is empty, to add a new element to the list, you only let the pfirst and plast links point to the new item. We mark the Nothing value of link of an element by crossed lines.

2.If the new element is to be added to the beginning of  the list, you will need to let the link of the new item points to the pfirst and then update the pfirst to point to the new item.

3. If the new element is to be added to the middle position of the list, you need to let a link point to the position immediately before the position that the new element will be placed in.

4. If the new element is to be added to the last of the list, you need to let the link of the plast point to the new element then update the plast to point the new element.

'VB.NET code to insert a new item to the linkedlist

Public Overrides Sub insert(ByVal val As Integer, ByVal pos As Integer)

Dim newnode As ListNode = New ListNode(val)
'empty list

If IsNothing(pfirst) And IsNothing(plast) Then

newnode.nextlk = Nothing
pfirst = newnode
plast = newnode
Console.WriteLine("Inserted:{0}", newnode.val)

'Insert at the beginning of the LinkedList
ElseIf (pos = 1) Then

newnode.nextlk = pfirst
pfirst = newnode
Console.WriteLine("Inserted:{0}", newnode.val)

'Insert in the middle of the list
ElseIf (pos > 1 And pos <= countitem()) Then

Dim ta As ListNode
Dim t As Integer
ta = pfirst
For t = 1 To pos - 1
ta = ta.nextlk
Next
newnode.nextlk = ta.nextlk
ta.nextlk = newnode
Console.WriteLine("Inserted:{0}", newnode.val)

ElseIf (pos = countitem() + 1) Then

newnode.nextlk = Nothing 'The next link of the item is null.
plast.nextlk = newnode
plast = newnode
Console.WriteLine("Inserted:{0}", newnode.val)

Else : Console.WriteLine("Invalid position!")
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.