From cfbd6490c8b03b820375f79ff4d009ed2d0252c3 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Kim=20Nguy=E1=BB=85n?= Date: Tue, 13 May 2014 14:36:20 +0200 Subject: [PATCH] Add two functions to the Node_list interface (and to the naive implementation): * pop discards the first element * append appends the element of the second argument at the end of the first one (in place). --- src/naive_node_list.ml | 22 ++++++++++++++++++++++ src/node_list.ml | 2 ++ 2 files changed, 24 insertions(+) diff --git a/src/naive_node_list.ml b/src/naive_node_list.ml index b6f0ae4..1b32c47 100644 --- a/src/naive_node_list.ml +++ b/src/naive_node_list.ml @@ -41,9 +41,22 @@ let iter f l = loop l.head + + let length l = l.length let is_empty l = l.head == nil +let pop l = + if is_empty l then failwith "pop" + else + let v = l.head.node in + let nhead = l.head.next in + l.head <- nhead; + if nhead == nil then l.last <- nil; + v + + + let add n l = let ncell = { node = n; next = nil } @@ -72,6 +85,15 @@ let push_front n l = l.length <- l.length + 1; end +let append l1 l2 = + let len2 = l2.length in + if len2 != 0 then begin + l1.length <- l1.length + len2; + l1.last.next <- l2.head; + l1.last <- l2.last; + end; + l1 + let head l = l.head let last l = l.last let next i = i.next diff --git a/src/node_list.ml b/src/node_list.ml index e9bb58a..1856bb8 100644 --- a/src/node_list.ml +++ b/src/node_list.ml @@ -23,6 +23,8 @@ module type S = val add : node -> t -> unit val push_front : node -> t -> unit val push_back : node -> t -> unit + val pop : t -> node + val append : t -> t -> t val iter : (node -> unit) -> t -> unit val length : t -> int val is_empty : t -> bool -- 2.17.1