I'm a relative new comer to development and need some assistance in writing a function. Here are the requirements:

Return the 5th element from the end in a singly linked list of integers, in one pass, and then provide a set of test cases against that function.

Any ideas?

Thanks

Indigo

Dani AI

Generated

confirmed VB6 and asked which VB — so here is a compact, VB6-friendly one-pass solution and test plan. Use the two-pointer (lead/follow) method: advance the lead pointer k steps, then advance both until lead is Nothing; follow will point to the kth-from-end. The implementation returns a Boolean and writes the integer via a ByRef parameter so callers can handle "not found" cleanly.

' Class module named ListNode
Option Explicit
Public Value As Long
Public NextNode As ListNode
' Standard module
Option Explicit

Public Function GetKthFromEnd(head As ListNode, k As Long, ByRef outValue As Long) As Boolean
    Dim lead As ListNode
    Dim follow As ListNode
    Dim i As Long

    If k <= 0 Then
        GetKthFromEnd = False
        Exit Function
    End If

    Set lead = head
    For i = 1 To k
        If lead Is Nothing Then
            GetKthFromEnd = False
            Exit Function
        End If
        Set lead = lead.NextNode
    Next i

    Set follow = head
    Do While Not lead Is Nothing
        Set lead = lead.NextNode
        Set follow = follow.NextNode
    Loop

    outValue = follow.Value
    GetKthFromEnd = True
End Function

Suggested test cases (run each and assert the Boolean + returned value):

  • Empty list => False.
  • Length 1..4 => False.
  • Length 5 => True, returns head.Value (5th-from-end).
  • Length 6 => True, returns node 2 value.
  • Lists with duplicate or negative values to verify it returns the correct node, not a value match.

Notes and cautions: this is O(n) time, O(1) extra space. In VB6 remember to use Set for object assignments and check for Nothing. If you prefer to return the ListNode instead of a value, change the signature to return a ListNode (or use ByRef for a node). Handle k<=0 explicitly to avoid ambiguous behavior.

Recommended Answers

All 2 Replies

In VB6? Or in VB.NET, or in another language altogether?

The function has to be coded in VB6.


Thanks

Imran

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.