Skip to content

Instantly share code, notes, and snippets.

@ZoomQuiet
Forked from aaruel/ElixirLinkedList.ex
Created October 20, 2020 08:07
Show Gist options
  • Save ZoomQuiet/08662d034809f90b05406974720adb5b to your computer and use it in GitHub Desktop.
Save ZoomQuiet/08662d034809f90b05406974720adb5b to your computer and use it in GitHub Desktop.
Elixir Linked List Implementation
defmodule LinkedList do
defstruct data: 0,
next: nil,
index: 0
def new(data \\ 0, index \\ 0) do
%__MODULE__{data: data, index: index}
end
def push(
curr = %__MODULE__{next: next, index: index},
data
) do
if next != nil do
%{curr | next: push(next, data)}
else
%{curr | next: new(data, index + 1)}
end
end
def size(%__MODULE__{next: next, index: index}) do
if !is_empty(next) do
size(next)
else
index + 1
end
end
def head(%__MODULE__{data: data}) do
data
end
def tail(%__MODULE__{data: data, next: next}) do
if !is_empty(next) do
tail(next)
else
data
end
end
def pop(%__MODULE__{next: next}) do
next
end
def is_empty(%__MODULE__{}) do
false
end
def is_empty(_) do
true
end
defp reverseimpl(list = %__MODULE__{next: next}, index, rev \\ nil) do
if !is_empty(next) do
reverseimpl(next, index - 1, %{list | next: rev, index: index})
else
%{list | next: rev, index: index}
end
end
def reverse(list = %__MODULE__{}) do
reverseimpl(list, size(list) - 1)
end
end
ll = LinkedList.new
|> LinkedList.push(1)
|> LinkedList.push(2)
|> LinkedList.push(3)
|> LinkedList.push(4)
|> LinkedList.push(5)
IO.inspect(ll |> LinkedList.reverse)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment