【发布时间】:2020-02-14 17:22:21
【问题描述】:
我正在尝试根据该列表中的节点是否满足返回布尔值的函数来从双向链接列表中删除元素。 由于某种原因,替换节点的前一个指针(已删除的下一个)没有更新,而是重新指向自身。
我的代码
(* The type of linked lists. *)
type 'a llist =
| Nil
| Cons of (float * 'a) * 'a lcell * 'a lcell
and 'a lcell = ('a llist) ref
let remove p head =
let rec remove' ll =
match !ll with
|Nil -> head := !head (*no node match*)
|Cons ((a, _), c, d) ->
if p a then
match (!c, !d) with
|(Nil, Nil) -> head := ref Nil (*singleton match*)
|(Cons(_, c', d'), Nil) -> (*last node match*)
d' := Nil
|(Nil, Cons(_, c', d')) -> (*first node match*)
head := d;
c':= Nil
|(Cons(_, _, d'), Cons(_, e', _))-> (*middle match; Does not work*)
e' := !c;
d' := !d
else
remove' d
in
remove' !head
测试结果
Initial value of head is
{contents =
@1:{contents =
Cons ((-1.689, 3),
@2:{contents = Nil},
@3:{contents =
Cons ((0.910, -1),
<@1>,
@4:{contents =
Cons ((0.647, 3),
<@3>,
@5:{contents =
Cons ((4.531, -1),
<@4>,
@6:{contents = Nil})})})})}}
Calling remove (fun x -> close x 0.646639313413) head (*close compares values accuracy up to two decimal digits*)
The value of head is now
{contents =
@1:{contents =
Cons ((-1.689, 3),
@2:{contents = Nil},
@3:{contents =
Cons ((0.910, -1),
<@1>,
@4:{contents =
Cons ((4.531, -1), <@4>, @5:{contents = Nil})})})}}
【问题讨论】:
标签: linked-list ocaml doubly-linked-list