Page 1 of 1

Moving element of a LinkedList...

Posted: Sat Aug 09, 2003 4:39 am
by Flype
Code updated for 5.20+. SwapElements() is now available for this.

i would like to move up or down the elements of a linked list and then display them in a listicongadget. So, i make some procedures but i think it's a bit tricky what i've done. Is there a more simple way to do the same ? Have a look, try and say me if it's good enough, thanx PBusers :wink:

Code: Select all

;/-------------------------------

#NONE   = -1
#BOTTOM = -1
#GT_LIST = 1
#GT_UP   = 2
#GT_DOWN = 3

;/-------------------------------

Global NewList mylist.s()

For i=0 To 20
  AddElement( mylist() ) : mylist() = "test line n°"+Str(i)
Next

;/-------------------------------

Procedure LIST_Fill()
  ClearGadgetItems( #GT_LIST )
  ResetList( mylist() )
  While NextElement( mylist() )
    AddGadgetItem( #GT_LIST, #BOTTOM, mylist(), 0 )
  Wend
EndProcedure

Procedure LIST_Up()
  position = GetGadgetState( #GT_LIST )
  If position <> #NONE
    SelectElement( mylist(), position )
    element.s = mylist()
    DeleteElement( mylist() )
    InsertElement( mylist() )
    mylist() = element
    LIST_Fill() : SetGadgetItemState( #GT_LIST, position-1, #True )
  EndIf
EndProcedure

Procedure LIST_Down()
  position = GetGadgetState( #GT_LIST )
  If position <> #NONE
    SelectElement( mylist(), position )
    element.s = mylist()
    DeleteElement( mylist() )
    SelectElement( mylist(), position+1 )
    InsertElement( mylist() )
    mylist() = element
    LIST_Fill() : SetGadgetItemState( #GT_LIST, position+1, #True )
  EndIf
EndProcedure

;/-------------------------------

OpenWindow( 0, 200, 200, 500, 400, "Nettie Prefs", #PB_Window_SystemMenu)
ListIconGadget( #GT_LIST, 60,5,WindowWidth(0)-65, WindowHeight(0)-10, "Item", 110, #PB_ListIcon_AlwaysShowSelection )
ButtonGadget( #GT_UP,   5,   5, 50, 24, "Up"   )
ButtonGadget( #GT_DOWN, 5,  30, 50, 24, "Down" )
LIST_Fill()

;/-------------------------------

Repeat
  Select WaitWindowEvent()
    Case #WM_CLOSE : quit=#True
    Case #PB_Event_Gadget
      Select EventGadget()
        Case #GT_UP   : LIST_Up()
        Case #GT_DOWN : LIST_Down()
      EndSelect
  EndSelect
Until quit=#True

;/-------------------------------

End

Posted: Sat Aug 09, 2003 1:02 pm
by Fred
It should be possible to do a simple pointer swapping but it's a bit lowlevel (but should be much faster):

Code: Select all

  Structure ListHeader
    *NextElement.ListHeader
    *PreviousElement.ListHeader
  EndStructure

  *MyElement = @list()-SizeOf(ListHeader)

  ; And you can play with the pointers :)

Posted: Mon Aug 11, 2003 7:42 am
by gnozal
@Fred :
Does your example also work for a 'structured' linked list with strings in it like :
Structure StringList
String.s
Long.l
EndStructure
NewList StringListExample.StringList
?

Posted: Mon Aug 11, 2003 10:49 am
by Fred
Yes.