Skip to content

Commit 0c17a1a

Browse files
author
Aleksandar Pokopec
committed
Queue - several bugs fixed, particular one not ...
Queue - several bugs fixed, particular one not updating the last0 field of MutableList.
1 parent 6aaab9a commit 0c17a1a

File tree

1 file changed

+34
-11
lines changed

1 file changed

+34
-11
lines changed

src/library/scala/collection/mutable/Queue.scala

Lines changed: 34 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -61,11 +61,25 @@ class Queue[A] extends MutableList[A] with Cloneable[Queue[A]] {
6161
first0 = first0.next
6262
len -= 1
6363
res
64-
} else
65-
extractFirst(first0, p) match {
66-
case None => None
67-
case Some(cell) => Some(cell.elem)
68-
}
64+
} else {
65+
val optElem = removeFromList(p)
66+
if (optElem != None) len -= 1
67+
optElem
68+
}
69+
70+
private def removeFromList(p: A => Boolean): Option[A] = {
71+
var leftlst = first0
72+
var res: Option[A] = None
73+
while (leftlst.next.nonEmpty && !p(leftlst.next.elem)) {
74+
leftlst = leftlst.next
75+
}
76+
if (leftlst.next.nonEmpty) {
77+
res = Some(leftlst.next.elem)
78+
if (leftlst.next eq last0) last0 = leftlst
79+
leftlst.next = leftlst.next.next
80+
}
81+
res
82+
}
6983

7084
/** Returns all elements in the queue which satisfy the
7185
* given predicate, and removes those elements from the queue.
@@ -84,13 +98,22 @@ class Queue[A] extends MutableList[A] with Cloneable[Queue[A]] {
8498
first0 = first0.next
8599
len -= 1
86100
}
87-
var cell: Option[LinkedList[A]] = extractFirst(first0, p)
88-
while (!cell.isEmpty) {
89-
res += cell.get.elem
90-
cell = extractFirst(cell.get, p)
91-
}
92-
res
101+
if (first0.isEmpty) res
102+
else removeAllFromList(p, res)
103+
}
104+
}
105+
106+
private def removeAllFromList(p: A => Boolean, res: ArrayBuffer[A]): ArrayBuffer[A] = {
107+
var leftlst = first0
108+
while (leftlst.next.nonEmpty) {
109+
if (p(leftlst.next.elem)) {
110+
res += leftlst.next.elem
111+
if (leftlst.next eq last0) last0 = leftlst
112+
leftlst.next = leftlst.next.next
113+
len -= 1
114+
} else leftlst = leftlst.next
93115
}
116+
res
94117
}
95118

96119
/** Return the proper suffix of this list which starts with the first element that satisfies `p`.

0 commit comments

Comments
 (0)