@@ -258,6 +258,26 @@ impl<T> DList<T> {
258
258
DList { list_head : None , list_tail : Rawlink :: none ( ) , length : 0 }
259
259
}
260
260
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
+
261
281
/// Add all elements from `other` to the end of the list
262
282
///
263
283
/// O(1)
@@ -688,6 +708,29 @@ mod tests {
688
708
}
689
709
}
690
710
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
+
691
734
#[ test]
692
735
fn test_iterator( ) {
693
736
let m = generate_test( ) ;
0 commit comments