Skip to main content

Find second last element of linked list in

Vb program for Find second last element of linked list. Here problem description and explanation.

' Include namespace system
Imports System 
' 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 = data = 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
            Me.tail.[next] = node
        End IF
        Me.tail = node
    End Sub
    '  Display linked list element
    Public Sub display()
        if (Me.head  Is  Nothing) Then
        End If
        Dim temp As LinkNode = Me.head
        '  iterating linked list elements
        while (temp IsNot Nothing)
            Console.Write( + " → ")
            '  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")
            '  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 : " + 
        End IF
    End Sub
    Public Shared Sub Main(ByVal args As String())
        Dim sll As SingleLL = New SingleLL()
        '  Add linked list node
        Console.WriteLine("Linked List")
        '  6 → 3 → 2 → 7 → 1 → 9 → null
    End Sub
End Class


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