Lua - List



We can implement a List, or more precisely Linked List easily. Lua table, being a dynamic data structure, will be used to implement a list.

What is Linked List?

A linked list is a linear data structure which can store a collection of "nodes" connected together via links i.e. pointers. Linked lists nodes are not stored at a contiguous location, rather they are linked using pointers to the different memory locations. A node consists of the data value and a pointer to the address of the next node within the linked list.

In Lua, each node can be representated by a table and link will be table field containing reference to the other table.

Linked Lists

A linked list starts with a head node which points to the first node. Every node consists of data which holds the actual data (value) associated with the node and a next pointer which holds the memory address of the next node in the linked list. The last node is called the tail node in the list which points to nil indicating the end of the list.

For more details on linked list, check out our page Linked List Data Structure.

Implementing Linked List in Lua

Let's start implementation of LinkedList

Create head element

head = nil

Insert an element at the begining of the list with a value.

function insert(node, value)
   node = {next = node, data = value}
   return node
end

Traverse the list

function traverse(head)
   local node = head
   while node do
      print(node.value)
      node = node.next
   end
end

Complete Example of a Linked List

In following example, we're adding multiple elements to a linked list and then printing each value.

main.lua

List = {}

-- insert an element at the beginning of the list
function List.insert(node, value)
   node = {next = node, data = value}
   return node
end

-- traverse the list and print all values
function List.traverse(head)
   local node = head
   while node do
      print(node.data)
      node = node.next
   end
end

-- create a head node
list = nil

-- insert values at the beginning of the List
list = List.insert(list, "Wednesday")
list = List.insert(list, "Tuesday")
list = List.insert(list, "Monday")

-- print values of the list
List.traverse(list)

Output

When we run the above program, we will get the following output−

Monday
Tuesday
Wednesday
Advertisements