How to create and use MutableLinkedList in Julia

Overview

The MutableLinkedList type in Julia is an implementation of a doubly-linked list. In this, the value of the nodes is mutable, or changeable.

The MutableLinkedList supports the insertion and removal of the elements at both ends of the list.

The elements are ordered in the insertion order.

Example

Below is a sample code for using MutableLinkedList in Julia:

using DataStructures
# Create new MultableLinkedList
list = MutableLinkedList{Int}()
## Add an element to the end of the list
push!(list, 1);
push!(list, 2);
push!(list, 3);
push!(list, 4);
println("The list is :", list);
pushfirst!(list, 0);
println("\nAdding 0 to the start of the list");
println("The list is :", list);
println("\nRemoving first element");
popfirst!(list)
println("The list is :", list);
println("\nRemoving last element");
pop!(list)
println("The list is :", list);
println("\nGet element at index 2");
println("The list is :", getindex(list, 2));

Explanation

  • Line 4: We create a MutableLinkedList object named list.
  • Lines 7–10: We use the push! method to insert four elements at the end of list.
  • Line 14: We use the pushfirst! method to insert one element at the beginning of list.
  • Line 20: We use the popfirst! method to remove the first element of list.
  • Line 20: We use the pop! method to remove the last element of list.
  • Line 21: We use the getindex! method to get the element at the 2 index.

Note: The complete reference to MutableLinkedList can be found on the official Julia page here.

Free Resources