Skip to content

Commit

Permalink
Simplifed the answer to dequeue
Browse files Browse the repository at this point in the history
  • Loading branch information
liuxinyu95 committed Apr 21, 2023
1 parent 64d2ca5 commit f19f620
Showing 1 changed file with 13 additions and 16 deletions.
29 changes: 13 additions & 16 deletions datastruct/elementary/queue/queue-zh-cn.tex
Original file line number Diff line number Diff line change
Expand Up @@ -685,27 +685,24 @@ \section{惰性实时队列}
双列表或双数组都可以实现双向队列。以双列表为例,定义两对操作:$push_l/pop_l$$push_r/pop_r$。在$pop_l/pop_r$时按需进行反转。以下实现每次按需反转一半元素。

\begin{Haskell}
data DeQueue a = DQ [a] Int [a] Int
empty = ([], [])

empty = DQ [] 0 [] 0
isEmpty ([], []) = True
isEmpty _ = False

isEmpty (DQ _ m _ n) = m == 0 && n == 0
pushL x (f, r) = (x:f, r)

pushL x (DQ f m r n) = DQ (x:f) (m + 1) r n
pushR (f, r) x = (f, x:r)

pushR (DQ f m r n) x = DQ f m (x:r) (n + 1)
popL ([], []) = (Nothing, empty)
popL ([], r) = let (as, bs) = splitAt (length r `div` 2) r in
popL (reverse bs, as)
popL (x:f, r) = (Just x, (f, r))

popL q@(DQ [] _ [] _) = (Nothing, q)
popL (DQ [] _ r n) = let m = n `div` 2
(as, bs) = splitAt m r in
popL (DQ (reverse bs) (n - m) as m)
popL (DQ (x:f) m r n) = (Just x, DQ f (m - 1) r n)

popR q@(DQ [] _ [] _) = (q, Nothing)
popR (DQ f m [] _) = let n = m `div` 2
(as, bs) = splitAt n f in
popR (DQ as n (reverse bs) (m - n))
popR (DQ f m (x:r) n) = (DQ f m r (n - 1), Just x)
popR ([], []) = (empty, Nothing)
popR (f , []) = let (as, bs) = splitAt (length f `div` 2) f in
popR (as, reverse bs)
popR (f, x:r) = ((f, r), Just x)
\end{Haskell}
}
\end{Answer}
Expand Down

0 comments on commit f19f620

Please sign in to comment.