ThinkGeek - Cool Stuff for Geeks and Technophiles

February 01, 2004

A linked list implementation

I hope this will be adult enough ;)

This is an implementation of a simple linked list. It needs some optimization (the method deleteElement relies on deleteElementAt, maybe I sholudn't use indexes to iterate trough the list,...) but it's a start. I will post an optimized version as soon as I finish it

Anyway, here's how it it works. To create an instance of the list, we have to pass it as a parameter an instance of a "comparator" class. That "comparator" class defines a lessThan() method that compares two objects. Depending of the kind of object we want to store in our list, we can define this method. For example, if we want to order the list depending on a property called "index", the "comparator class should look like this:

class net.designnation.structs.Comparador implements IOrder
{
 
 	function Comparador()
 	{
  	
  	}
 	
 	public function lessThan( firstComp: Object, secondComp: Object): Boolean
 	{
  		if (firstComp.index< secondComp.index)
  		{
   			return true;
   		}
  		else
  		{
   			return false;
   		}
  	}
}

So, we'll create an instance of the list like this:

import net.designnation.structs.*;

var myList:List = new List(new Comparador());

And then, to populate it...

myList.push({index:6, prop:"propvalue6"});
myList.insert({index:3, prop:"propvalue3"});

trace("Lista " + myList);

myList.insert({index:0, prop:"propvalue0"});
trace("Lista " + myList);

myList.insert({index:2, prop:"propvalue2"});
trace("Lista " + myList);

myList.insert({index:1, prop:"propvalue1"});
trace("Lista " + myList);

myList.insert({index:4, prop:"propvalue4"});
trace("Lista " + myList);

myList.insert({index:5, prop:"propvalue5"});
trace("Lista " + myList);

myList.insert({index:7, prop:"propvalue7"});
trace("Lista " + myList);

myList.insert({index:6, uno:"propvalue6"});
trace("Lista " + myList);
Download it here . Posted by Cesar Tardaguila Date: February 1, 2004 01:13 PM | TrackBack
Comments