Skip to content

Commit b71c3d2

Browse files
author
blake2-ppc
committed
dlist: Add .rotate_to_front(), .rotate_to_back()
Add methods to move back element to front or front element to back, without reallocating nodes.
1 parent 78d0cf1 commit b71c3d2

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/libextra/dlist.rs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,26 @@ impl<T> DList<T> {
258258
DList{list_head: None, list_tail: Rawlink::none(), length: 0}
259259
}
260260

261+
/// Move the last element to the front of the list.
262+
///
263+
/// If the list is empty, do nothing.
264+
#[inline]
265+
pub fn rotate_to_front(&mut self) {
266+
do self.pop_back_node().map_consume |tail| {
267+
self.push_front_node(tail)
268+
};
269+
}
270+
271+
/// Move the first element to the back of the list.
272+
///
273+
/// If the list is empty, do nothing.
274+
#[inline]
275+
pub fn rotate_to_back(&mut self) {
276+
do self.pop_front_node().map_consume |head| {
277+
self.push_back_node(head)
278+
};
279+
}
280+
261281
/// Add all elements from `other` to the end of the list
262282
///
263283
/// O(1)
@@ -688,6 +708,29 @@ mod tests {
688708
}
689709
}
690710

711+
#[test]
712+
fn test_rotate() {
713+
let mut n = DList::new::<int>();
714+
n.rotate_to_back(); check_links(&n);
715+
assert_eq!(n.len(), 0);
716+
n.rotate_to_front(); check_links(&n);
717+
assert_eq!(n.len(), 0);
718+
719+
let v = ~[1,2,3,4,5];
720+
let mut m = list_from(v);
721+
m.rotate_to_back(); check_links(&m);
722+
m.rotate_to_front(); check_links(&m);
723+
assert_eq!(v.iter().collect::<~[&int]>(), m.iter().collect());
724+
m.rotate_to_front(); check_links(&m);
725+
m.rotate_to_front(); check_links(&m);
726+
m.pop_front(); check_links(&m);
727+
m.rotate_to_front(); check_links(&m);
728+
m.rotate_to_back(); check_links(&m);
729+
m.push_front(9); check_links(&m);
730+
m.rotate_to_front(); check_links(&m);
731+
assert_eq!(~[3,9,5,1,2], m.consume_iter().collect());
732+
}
733+
691734
#[test]
692735
fn test_iterator() {
693736
let m = generate_test();

0 commit comments

Comments
 (0)