AddFirst/Last

BlitzMax Forums/BlitzMax Beginners Area/AddFirst/Last

pc_tek(Posted 2011) [#1]
In the example code I was given (kind regards to Czar)

Type TBall
	Global all:TList = New TList
	Field link:TLink
	
	Field x
	
	Method New()
		link = all.AddLast(Self)
	End Method
	
	Method remove()
		link.Remove()
		link = Null 'for safety
	End Method
	
	Function Create:TBall(x)
		Local ball:TBall = New TBall
		ball.x = x
		Return ball
	End Function
End Type

For Local i = 0 To 10
	TBall.Create(i)
Next

For Local ball:TBall = EachIn TBall.all
	ball.remove()
Next


How do I go about Addfirst (or last). I need to order certain balls in front or rear using the same code if possible.


jsp(Posted 2011) [#2]
While adding items first or last you can sort your list only to a certain extend.
Depending on your order it is may good to sort the list afterwards.
Use the Sortlist function to do so. (Example sorts by name of an imaginary MyObject)
SortList(myList, True, SortFunction)

Function SortFunction:Int(o1:MyObject, o2:MyObject)
    If o1.name < o2.name
        Return -1
    ElseIf o1.name > o2.name
        Return 1
    Else
        Return 0
    EndIf
End Function



pc_tek(Posted 2011) [#3]
The sorting would not be good for my game...I need either Addfirst or Addlast to be the solution.


Perturbatio(Posted 2011) [#4]
Can't you just add an optional parameter to the constructor that determines the insert position, defaulting it to last?


BladeRunner(Posted 2011) [#5]
If you need fast insert and remove, a TList may be the wrong option for you.
You could use a binary tree for example.


Jesse(Posted 2011) [#6]
you can do that by changing the new method to a function instead(untested but principle is exact):
    function AddFirst:Tball()
         local b:Tball = new Tball
         b.link = all.AddFirst(b)
         return b
   End Function 
   
   Function AddLast:Tball()
        local b:Tball = new Tball
        b.link = all.AddLast(b)
        return b
   End Function

if you just want to move an object first or last:
   method  moveFirst()
     remove()
     link = AddFirst(Self)
  End method

  method MoveLast()
      remove()
      link = addLast(self)
 end method


and all this is faster than a binary tree.

Last edited 2011