Skip to content

Commit 62974f6

Browse files
authored
Update algorithm8.rs
1 parent d9bf04c commit 62974f6

File tree

1 file changed

+15
-7
lines changed

1 file changed

+15
-7
lines changed

exercises/algorithm/algorithm8.rs

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
queue
33
This question requires you to use queues to implement the functionality of the stac
44
*/
5-
// I AM NOT DONE
65

76
#[derive(Debug)]
87
pub struct Queue<T> {
@@ -67,15 +66,24 @@ impl<T> myStack<T> {
6766
}
6867
}
6968
pub fn push(&mut self, elem: T) {
70-
//TODO
69+
self.q1.enqueue(elem);
7170
}
7271
pub fn pop(&mut self) -> Result<T, &str> {
73-
//TODO
74-
Err("Stack is empty")
72+
if self.q1.size() == 0 {
73+
return Err("Stack is empty");
74+
}
75+
while self.q1.size() > 1 {
76+
self.q2.enqueue(self.q1.dequeue().unwrap());
77+
}
78+
79+
let top = self.q1.dequeue().unwrap();
80+
81+
std::mem::swap(&mut self.q1, &mut self.q2);
82+
83+
Ok(top)
7584
}
7685
pub fn is_empty(&self) -> bool {
77-
//TODO
78-
true
86+
self.q1.is_empty()
7987
}
8088
}
8189

@@ -101,4 +109,4 @@ mod tests {
101109
assert_eq!(s.pop(), Err("Stack is empty"));
102110
assert_eq!(s.is_empty(), true);
103111
}
104-
}
112+
}

0 commit comments

Comments
 (0)