Main Menu

A question about Linked Lists

Started by Big C., July 28, 2010, 12:12:56 PM

Previous topic - Next topic

Big C.

I didn't know if this is the same issue as described here or a logical mistake...

PlayBASIC Code: [Select]
;
;Types
;
Type TBaseObj
X
Y
Status$
Sprite
Speed
EndType

Type TTest As TBaseObj
Height
DY
PlayerShot
EndType

Dim MyTestList As TTest List


For I = 1 To 5

MyTestList = New TTest

MyTestList.X = I
MyTestList.Y = I
MyTestList.Status$ ="Alive"
MyTestList.Height = I

Next

Print "ListSize: "+Str$(GetListSize(MyTestList()))
Print ""

For Each MyTestList()
Print "------ Begin ItemNo. "+Str$(GetListPos(MyTestList()))+" ------"
Print MyTestList.X
Print MyTestList.Y
Print MyTestList.Status$
Print MyTestList.Height
Print "------ End ItemNo. "+Str$(GetListPos(MyTestList()))+" ------"
Print ""
Next

Print "Direct Access: " + Str$(MyTestList.Height)

Sync
WaitKey



Why does the line Print "Direct Access: " + Str$(MyTestList.Height) put out zero as the result? I expected the value 5 from the ItemNo. 5 as described in the LinkedList Tutorial under the Headline Retrieving Information From a Linked List  ???

thx 4 answer

kevin


  When iterating through a linked list, the list pointer (which is held inside the list container) is moved to the next item each iteration.  At the end of the For EACH sequence, the internal pointer will be set at it's lists END position (zero), not the LAST item.

  So if we add 3 items to a list,  item A, B & C  (in that order) these would be stored in the list (assuming it was empty) as

   Item List Pos 1 =  A    links to #0 (END)
   Item List Pos  2=  B    links to #1
   Item List Pos  3=  C    links to #2


   So if we list these out

     For each MyList()
         print list.itetm
     next


  It'll spit out
  C
  B
  A

  At this point the internal list pointer is set the the END position.  If we access the list now, it'll be pointing at nothing.