55 */
66
77/* 基于环形数组实现的队列 */
8- struct ArrayQueue {
9- nums : Vec < i32 > , // 用于存储队列元素的数组
8+ struct ArrayQueue < T > {
9+ nums : Vec < T > , // 用于存储队列元素的数组
1010 front : i32 , // 队首指针,指向队首元素
1111 que_size : i32 , // 队列长度
1212 que_capacity : i32 , // 队列容量
1313}
1414
15- impl ArrayQueue {
15+ impl < T : Copy + Default > ArrayQueue < T > {
1616 /* 构造方法 */
17- fn new ( capacity : i32 ) -> ArrayQueue {
17+ fn new ( capacity : i32 ) -> ArrayQueue < T > {
1818 ArrayQueue {
19- nums : vec ! [ 0 ; capacity as usize ] ,
19+ nums : vec ! [ T :: default ( ) ; capacity as usize ] ,
2020 front : 0 ,
2121 que_size : 0 ,
2222 que_capacity : capacity,
@@ -39,7 +39,7 @@ impl ArrayQueue {
3939 }
4040
4141 /* 入队 */
42- fn push ( & mut self , num : i32 ) {
42+ fn push ( & mut self , num : T ) {
4343 if self . que_size == self . capacity ( ) {
4444 println ! ( "队列已满" ) ;
4545 return ;
@@ -53,7 +53,7 @@ impl ArrayQueue {
5353 }
5454
5555 /* 出队 */
56- fn pop ( & mut self ) -> i32 {
56+ fn pop ( & mut self ) -> T {
5757 let num = self . peek ( ) ;
5858 // 队首指针向后移动一位,若越过尾部,则返回到数组头部
5959 self . front = ( self . front + 1 ) % self . que_capacity ;
@@ -62,18 +62,18 @@ impl ArrayQueue {
6262 }
6363
6464 /* 访问队首元素 */
65- fn peek ( & self ) -> i32 {
65+ fn peek ( & self ) -> T {
6666 if self . is_empty ( ) {
6767 panic ! ( "index out of bounds" ) ;
6868 }
6969 self . nums [ self . front as usize ]
7070 }
7171
7272 /* 返回数组 */
73- fn to_vector ( & self ) -> Vec < i32 > {
73+ fn to_vector ( & self ) -> Vec < T > {
7474 let cap = self . que_capacity ;
7575 let mut j = self . front ;
76- let mut arr = vec ! [ 0 ; self . que_size as usize ] ;
76+ let mut arr = vec ! [ T :: default ( ) ; cap as usize ] ;
7777 for i in 0 ..self . que_size {
7878 arr[ i as usize ] = self . nums [ ( j % cap) as usize ] ;
7979 j += 1 ;
0 commit comments