List - Insert After

Monkey Forums/Monkey Programming/List - Insert After

QuietBloke(Posted 2011) [#1]
Hi All,

After what seems like forever I finally find I have some time to play with Monkey.
Just a quick question about lists

All I can see is methods to add to the top or bottom of a list. Is there something like an AddAfter() / AddBefore() ?


dawlane(Posted 2011) [#2]
Hi QB
Not quite sure of what you mean by AddAfter/AddBefore as to me they are the same add AddLast/AddFirst. But as a wild guess I would think that you are talking about adding to the list at a specific point? I think that is doable but you would pay a performance hit every time you called the routines.


AdamRedwoods(Posted 2011) [#3]
In my opinion, it's something that should be in Lists. Shouldn't be a performance hit adding a new link in, but the performance hit comes in doing the search.


NoOdle(Posted 2011) [#4]
take a look at stacks, they offer a bit more flexibility. You can get value by index, insert at specific index etc etc. Might be a suitable alternative? :)


QuietBloke(Posted 2011) [#5]
Thanks for the replies... After a rethink I decided to stick to using arrays instead. Im not too bothered about speed for the moment. If needed I may look at extending lists to do what Im after later.


AdamRedwoods(Posted 2011) [#6]
yeah, stacks is ok, it's based on arrays so an insert will take a long time (relatively).

So... I forgot there's an "insert" for Lists, it's just hidden. Here's code that runs through a List and inserts a new node.
MAKE SURE TO USE LATEST MONKEY VERSION (new list stuff was added).
Import mojo

Class Obj
	Field x:Int
	Field y:Int
	Field z:Int
	
	Method New(xx:Int,yy:Int,zz:Int)
		x=xx
		y=yy
		z=zz
	End
End


Class MyApp Extends App

	Field mylist:List<Obj>
		
	Method OnCreate()
		SetUpdateRate 30
		
		mylist = New List<Obj>
		mylist.AddLast(New Obj(1,1,1))
		mylist.AddLast(New Obj(2,2,2))
		mylist.AddLast(New Obj(3,3,3))
		
		Print "list:"
		
		For Local o:Obj = Eachin mylist
			Print o.x+" "+o.y+" "+o.z
		Next
		
		Print ""
		Print "list - insert"
		
		Local  mynode:list.Node<Obj> = mylist.FirstNode()
		Local insertdata:Obj = New Obj(9,9,9)
		
		While mynode
		
			If mynode.Value.x = 2
				''insert after
				New list.Node<Obj>(  mynode.NextNode(), mynode, insertdata)
			Endif
			
			mynode = mynode.NextNode() 
		Wend
		
		Print "list:"
		
		For Local o:Obj = Eachin mylist
			Print o.x+" "+o.y+" "+o.z
		Next
		
	End Method
	

	Method OnUpdate()

	End Method


	Method OnRender()
		
	End Method

End Class


Function Main()
	New MyApp()
End Function