Forum Discussion

roIt's avatar
roIt
Reel Rookie
6 years ago

Linked List implementation

Hi there,

I'd like to implement a Linked List of objects (https://en.wikipedia.org/wiki/Linked_list) in BritghtScript. The problem I am facing is that it seems there's no References to objects in BrightScript. I am not sure if I am missing something or if that's actually a case.

Any help would be appreciated.

3 Replies

  • Actually, there is a way you can do this.  If we assume a one-directional linked list, we can create a function that returns our object which stores some data for the node.  I'll start with a function that creates a node object and provides a method for setting the next object:

    function CreateNode(d)
    	node = {
    		SetNext	: function (x) : m.Next = x : return x : end function
    		GetNext : function () : return m.Next : end function
    		NextNode: Invalid
    		Data: d
    	}
    	return node
    end function

    My SetNext() function will take a node object and set its next object, returning the object for further manipulation.  I'll use GetNext() in order to walk the linked list later.  (You could simplify this a bit I'm sure since I'm very new to BrightScript).

    In my Main() function for testing purposes, I'll create a root node object, then add a few nodes to it.  I'll use a string for my node data, but you could use any other type of object you create (note the types are roAssociativeArray values for the nodes themselves).

    	' Create root node
    	root = CreateNode("Hello World! ")
    	
    	' Add nodes to each one returned
    	nextNode = root.SetNext(CreateNode("Hello Next Node! "))
    	nextNode = nextNode.SetNext(CreateNode("Another Node! "))
    	nextNode = nextNode.SetNext(CreateNode("Last Node!"))
    	
    	' Start from root
    	node = root
    	result = ""
    	
    	' Walk nodes until no more found
    	while node <> Invalid
            result = result + node.Data
    		node = node.GetNext()
    	end while
    	
    	' Print the combined string
    	print result

    If you run upload this app, compile and run it, you should see the following in the developer console:

    Hello World! Hello Next Node! Another Node! Last Node!

    Cheers!

    • roIt's avatar
      roIt
      Reel Rookie

      This looks like a great suggestion! Will try it out, thanks!

  • Associative arrays can be used like objects. Maybe that's what you're missing.