Skip to content

Instantly share code, notes, and snippets.

@bojidar-bg
Last active July 22, 2024 21:38
Show Gist options
  • Save bojidar-bg/a570c614a4dd1cd84949 to your computer and use it in GitHub Desktop.
Save bojidar-bg/a570c614a4dd1cd84949 to your computer and use it in GitHub Desktop.
DEPRECATED Linked List for Godot -- see link below

WARNING ⚠️ Deprecated. Use https://gist.github.com/belzecue/6253c8c694d602e715fff0b3f4303344/ instead.

Old usage sample:
const LinkedList = preload("LinkedList.gd")

func _ready():
	var ll = LinkedList.new()
	ll.push_back(-1)
	ll.push_back(5)
	ll.push_front(1)
	ll.push_front(2)
	print(ll.size()) # 4
	print(ll.pop_best(funcref(self, "comp"))) # 5
	print(ll.pop_back()) # -1
	print(ll.pop_front()) # 2
	print(ll.size()) # 1

func comp(a,b):
	return a > b
</details>
##
## WARNING: Deprecated. Use https://gist.github.com/belzecue/6253c8c694d602e715fff0b3f4303344/ instead.
##
extends Reference
class LinkedListItem:
extends Reference
var next = null
var previous = null
var data = {}
func _init(v):
data = v
func link(other):
other.previous = self
next = other
func unlink():
var _next = next
var _previous = previous
if _previous:
_previous.next = next
if _next:
_next.previous = previous
var _tail = null
var _head = _tail
var _len = 0
func size():
return _len
func push_back(val):
if _len == 0:
_head = LinkedListItem.new(val)
_tail = _head
else:
var new_head = LinkedListItem.new(val)
_head.link(new_head)
_head = new_head
_len += 1
func push_front(val):
if _len == 0:
_head = LinkedListItem.new(val)
_tail = _head
else:
var new_tail = LinkedListItem.new(val)
new_tail.link(_tail)
_tail = new_tail
_len += 1
func pop_back():
if _len == 0:
return null
else:
var result = _head.data
_head = _head.previous
_len -= 1
return result
func pop_front():
if _len == 0:
return null
else:
var result = _tail.data
_tail = _tail.next
_len -= 1
return result
func pop_best(better_func):
if _len == 0:
return null
else:
var current_best = _tail
var next = _tail.next
while next:
if not better_func.call_func(current_best.data, next.data):
current_best = next
next = next.next
if _head == current_best:
return pop_back()
if _tail == current_best:
return pop_front()
else:
current_best.unlink()
return current_best.data
##
## WARNING: Deprecated. Use https://gist.github.com/belzecue/6253c8c694d602e715fff0b3f4303344/ instead.
##
@belzecue
Copy link

No worries, happy to maintain a fork (which includes the swapped code mentioned in my prior comment).

https://gist.github.com/belzecue/6253c8c694d602e715fff0b3f4303344/

@bojidar-bg
Copy link
Author

Alrighty, thanks! 😊 Updated the readme and script to link to your gist (: -- you might want to change the first few lines of your LinkedList.gd to reflect that too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment