昨天一边看着官网docs一边学习Julia的产物,用到了复合类型、参数化类型和迭代器
不知道写法是否合适,总之发上来欢迎指正
module SinglyLinkedList
export Node,HeadNode,DataNode
abstract type Node{T} end
mutable struct DataNode{T}<:Node{T}
next::Union{DataNode{T},Nothing}
data::T
end
DataNode{T}(data::T) where T=DataNode{T}(nothing,data)
mutable struct HeadNode{T}<:Node{T}
next::Union{DataNode{T},Nothing}
size::Integer
HeadNode{T}() where T=new{T}(nothing,0)
end
function Base.pushfirst!(head::HeadNode{T},x::T) where T
nextnode=head.next
head.next=DataNode{T}(nextnode,x)
head.size+=1
return head
end
function Base.push!(head::HeadNode{T},x::T) where T
cur=head
while cur.next!=nothing
cur=cur.next
end
cur.next=DataNode{T}(x)
head.size+=1
return head
end
function Base.popfirst!(head::HeadNode)
first=head.next
if first==nothing
throw(ArgumentError("list must be non-empty"))
end
head.next=head.next.next
head.size-=1
return first.data
end
function Base.pop!(head::HeadNode)
cur=head
prev=nothing
while cur.next!=nothing
prev=cur
cur=cur.next
end
if prev==nothing
throw(ArgumentError("list must be non-empty"))
end
prev.next=nothing
head.size-=1
return cur.data
end
function Base.insert!(head::HeadNode{T},pos::Node{T},x::T) where T
nextnode=pos.next
pos.next=DataNode{T}(x)
head.size+=1
pos.next.next=nextnode
end
function Base.reverse!(head::HeadNode)
cur=head.next
if cur==nothing
return
end
while cur.next!=nothing
nextnode=cur.next.next
cur.next.next=head.next
head.next=cur.next
cur.next=nextnode
end
return head
end
Base.length(head::HeadNode)=head.size
Base.eltype(head::HeadNode{T}) where T=T
function Base.iterate(head::HeadNode)
first=head.next
if first==nothing
return nothing
else
return (first.data,first)
end
end
function Base.iterate(head::HeadNode,cur::Node)
cur=cur.next
if cur==nothing
return nothing
else
return (cur.data,cur)
end
end
Base.show(io::IO,head::HeadNode)=Base.show_delim_array(io,head,"[","->","]",false)
end
使用
julia> using SinglyLinkedList
julia> h=HeadNode{Int}()
[]
julia> push!(h,2,3,5)
[2-> 3-> 5]
julia> pushfirst!(h,1)
[1-> 2-> 3-> 5]
julia> let
next=iterate(h)
while next!=nothing
(x,s)=next
if x==3
insert!(h,s,4)
end
next=iterate(h,s)
end
end
julia> h
[1-> 2-> 3-> 4-> 5]
julia> reverse!(h)
[5-> 4-> 3-> 2-> 1]
julia> popfirst!(h)
5
julia> while !isempty(h)
println(pop!(h))
end
1
2
3
4
另外REPL里面如果我不用let包起来语句的话会报错next未定义,不太清楚成因