Find second last element of linked list in vb.net
Vb program for Find second last element of linked list. Here problem description and explanation.
' Include namespace system
Imports System
' Vb.net program for
' Find the second last node of a linked list
' Node of Linked List
Public Class LinkNode
Public data As Integer
Public [next] As LinkNode
Public Sub New(ByVal data As Integer)
' Set node value
Me.data = data
Me.next = Nothing
End Sub
End Class
public Class SingleLL
Public head As LinkNode
Public tail As LinkNode
Public Sub New()
' Set head and tail
Me.head = Nothing
Me.tail = Nothing
End Sub
' Add new node at the end of linked list
Public Sub insert(ByVal value As Integer)
' Create a new node
Dim node As LinkNode = New LinkNode(value)
if (Me.head Is Nothing) Then
Me.head = node
Else
Me.tail.[next] = node
End IF
Me.tail = node
End Sub
' Display linked list element
Public Sub display()
if (Me.head Is Nothing) Then
Return
End If
Dim temp As LinkNode = Me.head
' iterating linked list elements
while (temp IsNot Nothing)
Console.Write(temp.data.ToString() + " → ")
' Visit to next node
temp = temp.[next]
End While
Console.Write("null"& vbLf )
End Sub
' Find the second last node of a linked list
Public Sub secondLast()
Dim node As LinkNode = Me.head
if (node Is Nothing) Then
Console.Write("Empty linked list")
ElseIf (node.[next] Is Nothing) Then
Console.Write("Only one node in this linked list")
Else
' Find second last node
while (node.[next] IsNot Nothing AndAlso
node.[next].[next] IsNot Nothing)
' Visit to second next node
node = node.[next].[next]
End While
Console.WriteLine("Second last element is : " +
node.data.ToString())
End IF
End Sub
Public Shared Sub Main(ByVal args As String())
Dim sll As SingleLL = New SingleLL()
' Add linked list node
sll.insert(6)
sll.insert(3)
sll.insert(2)
sll.insert(7)
sll.insert(1)
sll.insert(9)
Console.WriteLine("Linked List")
' 6 → 3 → 2 → 7 → 1 → 9 → null
sll.display()
sll.secondLast()
End Sub
End Class
Output
Linked List
6 → 3 → 2 → 7 → 1 → 9 → null
Second last element is : 1
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment