Quick Links: Download Gideros Studio | Gideros Documentation | Gideros community chat | DONATE
Double Linked List — Gideros Forum

Double Linked List

GregBUGGregBUG Guru
edited February 2012 in Code snippets
may be useful to someone...
a simple double linked list class:
CDLinkedList = Core.class()
 
----------------------------
-- Init width a void list --
----------------------------
function CDLinkedList:init()
	self.list = {
		first		= nil, 
		last		= nil,
	}
	self.itemsCount = 0
end
 
-----------------------------
-- add an item to the list --
-----------------------------
function CDLinkedList:add(objectData)
	self.newItem = {
		prev = nil, 
		next = self.list.first, 
		data = objectData
	}
	self.itemsCount = self.itemsCount + 1
	if not self.list.first then
		self.list.first = self.newItem
		self.list.last = self.newItem
	else
		self.list.first.prev = self.newItem
		self.list.first = self.newItem
	end
end
 
--------------------------------
-- delete an item to the list --
--------------------------------
function CDLinkedList:delete(node)
	if node == self.list.first then
		self.list.first = node.next
	else
		node.prev.next = node.next
	end
 
	if node == self.list.last then
		self.list.last = node.prev
	else
		node.next.prev = node.prev
	end
	self.itemsCount = self.itemsCount - 1
end
 
-------------------------------
-- for iterate with for loop --
-------------------------------
function getNext(list, node)
	return (not node and list.last) or node.prev
end
 
--- DEMO ---
 
 
 
local mylist = CDLinkedList.new()
 
for j = 1, 100 do
	mylist:add("ITEM "..j)
end
 
for node in getNext, mylist.list do
	print(node.data)
end

Likes: atilim

TNT ENGiNE for Gideors Studio - Particle Engine, Virtual Pad, Animator Studio, Collision Engine - DOWNLOAD NOW !!! IT'S FREE!!! -
www.tntengine.com
+1 -1 (+1 / -0 )Share on Facebook
Sign In or Register to comment.