SZman
SZman

Reputation: 141

Inserting new nodes while iterating through a linked list

I am trying to make an ordered linked list of tuples in VB.NET. Currently I am having issues with the sorting part. Currently, I am just iterating through when I insert a new node and Using an AddBefore or an AddAfter, but I keep getting syntax errors.

For node In LinkedList
    If node.Item1 < results.Item1 Then
        LinkedList.AddBefore(node, newnode)
    ElseIf node.Item1 = results.Item1 Then
        LinkedList.AddAfter(node, newnode)
    ElseIf LinkedList.Last.Equals(node) Then
        LInkedList.AddLast(results)
    End If
Next

It just says that there is a syntax error and when I try this:

For Each node In LinkedList
    If node.Item1 < results.Item1 Then
        LinkedList.AddBefore(node, newnode)
    ElseIf node.Item1 = results.Item1 Then
        LinkedList.AddAfter(node, newnode)
    ElseIf LinkedList.Last.Equals(node) Then
        LInkedList.AddLast(results)
    End If
Next

I get an error that the node is not the appropriate type so AddBefore and AddAfter will not work. How can I fix this problem?

The newnode is created like this:

newnode = New LinkedListNode(Of Tuple(Of Double, String))(results)

Upvotes: 0

Views: 1325

Answers (1)

Phillip Trelford
Phillip Trelford

Reputation: 6543

The AddBefore, AddAfter and AddLast members expect a node as the first parameter. When using For Each over a LinkedList the values are returned not the nodes.

To iterate over the nodes of a LinkedList you can use the First property to get the first node and then Next on each node. To get at the value of each node you must use the Value property:

    Dim node = linkedList.First
    While node IsNot Nothing
        If node.Value.Item1 < results.Item1 Then
            linkedList.AddBefore(node, newnode)
        ElseIf node.Value.Item1 = results.Item1 Then
            linkedList.AddAfter(node, newnode)
        ElseIf linkedList.Last.Equals(node) Then
            linkedList.AddLast(results)
        End If
        node = node.Next
    End While

Another option would be to use System.Collections.Generic.SortedDictionary which automatically sorts on the key.

Upvotes: 1

Related Questions