Skip to content

Commit 39c5c45

Browse files
committed
make array deque generic
1 parent fffc187 commit 39c5c45

1 file changed

Lines changed: 13 additions & 13 deletions

File tree

codes/rust/chapter_stack_and_queue/array_deque.rs

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,17 @@
55
*/
66
use hello_algo_rust::include::print_util;
77
/* 基于环形数组实现的双向队列 */
8-
struct ArrayDeque {
9-
nums: Vec<i32>, // 用于存储双向队列元素的数组
8+
struct ArrayDeque<T> {
9+
nums: Vec<T>, // 用于存储双向队列元素的数组
1010
front: usize, // 队首指针,指向队首元素
1111
que_size: usize, // 双向队列长度
1212
}
1313

14-
impl ArrayDeque {
14+
impl<T: Copy + Default> ArrayDeque<T> {
1515
/* 构造方法 */
1616
pub fn new(capacity: usize) -> Self {
1717
Self {
18-
nums: vec![0; capacity],
18+
nums: vec![T::default(); capacity],
1919
front: 0,
2020
que_size: 0,
2121
}
@@ -41,11 +41,11 @@ impl ArrayDeque {
4141
// 通过取余操作实现数组首尾相连
4242
// 当 i 越过数组尾部后,回到头部
4343
// 当 i 越过数组头部后,回到尾部
44-
return ((i + self.capacity() as i32) % self.capacity() as i32) as usize;
44+
((i + self.capacity() as i32) % self.capacity() as i32) as usize
4545
}
4646

4747
/* 队首入队 */
48-
pub fn push_first(&mut self, num: i32) {
48+
pub fn push_first(&mut self, num: T) {
4949
if self.que_size == self.capacity() {
5050
println!("双向队列已满");
5151
return;
@@ -59,7 +59,7 @@ impl ArrayDeque {
5959
}
6060

6161
/* 队尾入队 */
62-
pub fn push_last(&mut self, num: i32) {
62+
pub fn push_last(&mut self, num: T) {
6363
if self.que_size == self.capacity() {
6464
println!("双向队列已满");
6565
return;
@@ -72,7 +72,7 @@ impl ArrayDeque {
7272
}
7373

7474
/* 队首出队 */
75-
fn pop_first(&mut self) -> i32 {
75+
fn pop_first(&mut self) -> T {
7676
let num = self.peek_first();
7777
// 队首指针向后移动一位
7878
self.front = self.index(self.front as i32 + 1);
@@ -81,22 +81,22 @@ impl ArrayDeque {
8181
}
8282

8383
/* 队尾出队 */
84-
fn pop_last(&mut self) -> i32 {
84+
fn pop_last(&mut self) -> T {
8585
let num = self.peek_last();
8686
self.que_size -= 1;
8787
num
8888
}
8989

9090
/* 访问队首元素 */
91-
fn peek_first(&self) -> i32 {
91+
fn peek_first(&self) -> T {
9292
if self.is_empty() {
9393
panic!("双向队列为空")
9494
};
9595
self.nums[self.front]
9696
}
9797

9898
/* 访问队尾元素 */
99-
fn peek_last(&self) -> i32 {
99+
fn peek_last(&self) -> T {
100100
if self.is_empty() {
101101
panic!("双向队列为空")
102102
};
@@ -106,9 +106,9 @@ impl ArrayDeque {
106106
}
107107

108108
/* 返回数组用于打印 */
109-
fn to_array(&self) -> Vec<i32> {
109+
fn to_array(&self) -> Vec<T> {
110110
// 仅转换有效长度范围内的列表元素
111-
let mut res = vec![0; self.que_size];
111+
let mut res = vec![T::default(); self.que_size];
112112
let mut j = self.front;
113113
for i in 0..self.que_size {
114114
res[i] = self.nums[self.index(j as i32)];

0 commit comments

Comments
 (0)