Last active
May 28, 2024 22:34
-
-
Save aaruel/3b4cfac8be09f3eec31e8fe7db295834 to your computer and use it in GitHub Desktop.
Elixir Linked List Implementation
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
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
ty!