Last active
August 3, 2023 11:35
-
-
Save LouiseBC/692bfd907d9e0527b471947d540dee6c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Circular, doubly linked list -- | |
---------------------------------- | |
local linkedList = {} | |
-- Creates a list from table or variable n. of values -- | |
function linkedList.construct(...) | |
local args = {...} | |
local tail = linkedList.newNode(args[1]) | |
for i = 2, #args do | |
linkedList.insert(tail, args[i]) | |
tail = tail.next | |
end | |
return tail.next | |
end | |
-- Creates a new instance of node -- | |
function linkedList.newNode(val) | |
local node = {} | |
node.value = val | |
node.next = node | |
node.prev = node | |
return node | |
end | |
-- Inserts a node after the given node && returns a reference -- | |
function linkedList.insert(node, val) | |
local newnode = linkedList.newNode(val) | |
newnode.next = node.next | |
newnode.prev = node | |
node.next = newnode | |
return newnode | |
end | |
-- Remove an element of the list, return reference to next element -- | |
function linkedList.erase(node) | |
local index = node.next | |
node.prev.next = node.next | |
node = nil | |
return index | |
end | |
-- Print the whole list, avoiding circularity -- | |
function linkedList.print(node) | |
local it = node | |
repeat | |
print(it.value) | |
it = it.next | |
until it == node | |
end | |
return linkedList |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local list = require("LinkedList") | |
foo = list.construct(1, 2, 3, 4, 5, 6) | |
list.print(foo) print() | |
-- Output: 1, 2, 3, 4, 5, 6 -- | |
list.print(foo.next.next) print() | |
-- Output: 3, 4, 5, 6, 1, 2 -- | |
last = list.insert(foo.prev, 'bar') | |
list.print(last) print() | |
-- Output: 'bar', 2, 3, 4, 5, 6, 1 | |
-- Oops: first in list doesn't refer to last -- | |
-- Don't know how to do this without storing additional information -- | |
last = list.erase(last) | |
list.print(last) | |
-- Output: 2, 3, 4, 5, 6, 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment