algori 0.13.0

Rust Algorithms
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
#[cfg(not(feature = "no_std"))]
use core::{fmt::Display, ptr::NonNull};

// 节点
#[cfg(not(feature = "no_std"))]
#[derive(Debug)]
struct Node<T> {
    next: Option<NonNull<Node<T>>>,
    prev: Option<NonNull<Node<T>>>,
    element: T,
}

#[cfg(not(feature = "no_std"))]
#[derive(Debug)]
/// LinkedList(双向)
pub struct LinkedList<T> {
    head: Option<NonNull<Node<T>>>,
    tail: Option<NonNull<Node<T>>>,
    len: usize,
    // marker表示本结构有一个Box<Node<T>>的所有权
    // 链表的节点申请和释放都是通过Box<T>完成 所以拥有所有权
    marker: core::marker::PhantomData<Box<Node<T>>>,
}
#[cfg(not(feature = "no_std"))]
impl<T> Node<T> {
    fn new(element: T) -> Self {
        return Node {
            next: None,
            prev: None,
            element,
        };
    }
    fn into_element(self) -> T {
        return self.element; // 消费Box后 堆内存释放 并复制element到栈
    }
}
#[cfg(not(feature = "no_std"))]
impl<T> Default for LinkedList<T> {
    fn default() -> Self {
        return Self::new();
    }
}
#[cfg(not(feature = "no_std"))]
impl<T> LinkedList<T> {
    /// 构造空的双向链表
    pub const fn new() -> Self {
        return LinkedList {
            head: None,
            tail: None,
            len: 0usize,
            marker: core::marker::PhantomData,
        };
    }
    /// 返回尾的引用
    pub fn back(&self) -> Option<&T> {
        if let Some(tail) = self.tail {
            unsafe {
                return Some(&(*tail.as_ptr()).element);
            }
        } else {
            // 尾为空
            return None;
        }
    }
    /// 返回头的引用
    pub fn front(&self) -> Option<&T> {
        if let Some(head) = self.head {
            unsafe {
                return Some(&(*head.as_ptr()).element);
            }
        } else {
            // 头为空
            return None;
        }
    }

    /// 在链表尾部追加节点
    pub fn push_back(&mut self, element: T) {
        let mut new_node = Box::new(Node::new(element));
        // 新节点的prev指向链表的尾部
        new_node.prev = self.tail;
        // 转换为NonNull指针
        let new_node = NonNull::new(Box::into_raw(new_node));
        match self.tail {
            Some(node) => {
                // 旧尾部需要解引用裸指针
                unsafe {
                    // 链表尾部的next指向新节点
                    (*node.as_ptr()).next = new_node;
                }
            }
            // 链表头部指向新节点
            None => self.head = new_node,
        }
        // 链表尾部指向新节点
        self.tail = new_node;
        self.len += 1;
    }
    /// 在链表尾部追加节点
    pub fn push_front(&mut self, element: T) {
        let mut new_node = Box::new(Node::new(element));
        // 新节点的next指向链表的头部
        new_node.next = self.head;
        // 转换为NonNull指针
        let new_node = NonNull::new(Box::into_raw(new_node));
        match self.head {
            Some(node) => {
                // 旧头部需要解引用裸指针
                unsafe {
                    // 链表尾部的next指向新节点
                    (*node.as_ptr()).prev = new_node;
                }
            }
            // 链表尾部指向新节点
            None => self.tail = new_node,
        }
        // 链表头部指向新节点
        self.head = new_node;
        self.len += 1;
    }
    /// 返回链表长度
    pub fn len(&self) -> usize {
        return self.len;
    }

    /// 根据给出的index(节点的序号) 插入到index
    /// ```
    /// use algori::structure::LinkedList;
    /// let mut a = LinkedList::new();
    /// a.push_back(0);
    /// a.push_back(0);
    /// a.push_back(1);
    /// a.push_front(2);
    /// a.insert(1,9);
    /// a.insert(3,10);
    ///
    /// ```
    ///
    pub fn insert(&mut self, index: usize, element: T) -> Result<(), String> {
        // 索引越界
        if self.len < index {
            return Err(format!(
                "LinkedList len is {}, but index is {}",
                self.len, index
            ));
        }
        // 链表为空 或 索引为0,插入开头
        if index == 0 || self.head.is_none() {
            self.push_front(element);
            return Ok(());
        }
        // 索引在尾,插入结尾
        if self.len == index {
            self.push_back(element);
            return Ok(());
        }
        // 遍历到插入点
        if let Some(mut current_node) = self.head {
            for _ in 0..index {
                unsafe {
                    match (*current_node.as_ptr()).next {
                        None => {
                            return Err(format!(
                                "LinkedList len is {}, but index is {}",
                                self.len, index
                            ))
                        }
                        Some(next_ptr) => current_node = next_ptr,
                    }
                }
            }
            // 创建新节点
            let mut new_node = Box::new(Node::new(element));
            unsafe {
                new_node.prev = (*current_node.as_ptr()).prev;
                new_node.next = Some(current_node);
            }
            unsafe {
                if let Some(old_prev) = (*current_node.as_ptr()).prev {
                    let node_ptr = NonNull::new(Box::into_raw(new_node));
                    // 更改插入点前面节点的next
                    (*old_prev.as_ptr()).next = node_ptr;
                    // 更改插入点前面节点的prev
                    (*current_node.as_ptr()).prev = node_ptr;
                    self.len += 1;
                }
            }
        }

        Ok(())
    }
    /// 弹出链表头部元素 若头部为None则返回None
    /// ```
    /// use algori::structure::LinkedList;
    /// let mut a = LinkedList::new();
    /// a.push_back(0);
    /// a.push_back(0);
    /// a.push_back(1);
    /// a.push_front(2);
    /// a.insert(1,9);
    /// a.insert(3,10);
    /// assert_eq!(a.pop_front(),Some(2));
    /// ```
    pub fn pop_front(&mut self) -> Option<T> {
        // 获取头部元素
        if let Some(node) = self.head {
            unsafe {
                // 旧头的next
                if let Some(new_head) = (*node.as_ptr()).next {
                    // 新头的prev变成None
                    (*new_head.as_ptr()).prev = None;
                    // 旧头获得所有权
                    let node = Box::from_raw(node.as_ptr());
                    // head指向旧头的next
                    self.head = Some(new_head);
                    // 返回旧头的元素
                    return Some(node.into_element());
                } else {
                    // 当头的next为None时
                    // 将头也设置为None
                    if let Some(head) = self.head {
                        self.head = None;
                        let node = Box::from_raw(head.as_ptr());
                        return Some(node.into_element());
                    }
                }
            }
            // 头部为空 返回None
        }
        return None;
    }
    /// 弹出链表尾部元素 若头部为None则返回None
    /// ```
    /// use algori::structure::LinkedList;
    /// let mut a = LinkedList::new();
    /// a.push_back(0);
    /// a.push_back(0);
    /// a.push_back(1);
    /// a.push_front(2);
    /// a.push_back(9);
    /// a.insert(1,9);
    /// a.insert(3,10);
    /// assert_eq!(a.pop_back(),Some(9));
    /// ```
    pub fn pop_back(&mut self) -> Option<T> {
        // 获取尾部元素
        if let Some(node) = self.tail {
            unsafe {
                // 旧尾的prev
                if let Some(new_tail) = (*node.as_ptr()).prev {
                    // 新尾的next变成None
                    (*new_tail.as_ptr()).next = None;
                    // 旧尾获得所有权
                    let node = Box::from_raw(node.as_ptr());
                    // tail指向旧尾的prev
                    self.tail = Some(new_tail);
                    // 返回旧尾的元素
                    return Some(node.into_element());
                } else {
                    // 当尾的next为None时
                    // 将尾也设置为None
                    if let Some(tail) = self.tail {
                        self.tail = None;
                        let node = Box::from_raw(tail.as_ptr());
                        return Some(node.into_element());
                    }
                }
            }
            // 尾部为空 返回None
        }
        return None;
    }
    /// 弹出链表位于index的元素
    /// ```
    /// use algori::structure::LinkedList;
    /// let mut a = LinkedList::new();
    /// a.push_back(0);
    /// a.push_back(0);
    /// a.push_back(1);
    /// a.push_front(2);
    /// a.insert(1,9);
    /// a.insert(3,10);
    /// a.insert(4,232);
    /// assert_eq!(Some(232),a.pop(4));
    /// ```
    ///
    pub fn pop(&mut self, index: usize) -> Option<T> {
        // 索引越界
        if self.len < index {
            return None;
        }
        // 链表为空 或 索引为0,插入开头
        if index == 0 || self.head.is_none() {
            return self.pop_front();
        }
        // 索引在尾,插入结尾
        if self.len == index {
            return self.pop_back();
        }

        if let Some(mut current_node) = self.head {
            // 遍历到插入点
            for _ in 0..index {
                unsafe {
                    match (*current_node.as_ptr()).next {
                        None => {
                            return None;
                        }
                        Some(next_ptr) => current_node = next_ptr,
                    }
                }
            }
            unsafe {
                // 插入点前一个节点
                if let Some(prev_node) = (*current_node.as_ptr()).prev {
                    // 插入点后一个节点
                    if let Some(next_node) = (*current_node.as_ptr()).next {
                        // 前一个节点的next指向后一个节点的prev
                        (*prev_node.as_ptr()).next = Some(next_node);
                        // 后一个节点的prev指向前一个节点的next
                        (*next_node.as_ptr()).prev = Some(prev_node);
                    }
                }
            }
            // 获得删除节点所有权
            unsafe {
                let delete_node = Box::from_raw(current_node.as_ptr());
                return Some(delete_node.into_element());
            }
        }

        None
    }
    /// 返回index的节点元素的引用
    /// ```
    /// use algori::structure::LinkedList;
    /// let mut a = LinkedList::new();
    /// a.push_back(0);
    /// a.push_back(0);
    /// a.push_back(1);
    /// a.push_front(2);
    /// a.insert(1,9);
    /// a.insert(3,10);
    /// a.insert(4,232);
    /// assert_eq!(Some(&232),a.get(4));
    /// ```
    pub fn get(&self, index: usize) -> Option<&T> {
        // 索引越界
        if self.len < index || self.head.is_none() {
            return None;
        }
        //        if index == 0 {
            if let Some(element) = self.head {
                unsafe {
                    return Some(&(*element.as_ptr()).element);
                }
            }
        }
        if let Some(mut current_node) = self.head {
            // 遍历到点
            for _ in 0..index {
                unsafe {
                    match (*current_node.as_ptr()).next {
                        None => {
                            return None;
                        }
                        Some(next_ptr) => current_node = next_ptr,
                    }
                }
            }
            unsafe {
                return Some(&(*current_node.as_ptr()).element);
            }
        }
        None
    }
    /// 消耗linkedlist变成vec
    pub fn to_vec(mut self) -> Vec<T> {
        let mut vec = vec![];
        while self.head.is_some() {
            if let Some(value) = self.pop_front() {
                vec.push(value);
            }
        }
        return vec;
    }
}
#[cfg(not(feature = "no_std"))]
impl<T> Display for LinkedList<T>
where
    T: Display,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        if self.len == 0 {
            return Ok(());
        }
        if let Some(mut current_node) = self.head {
            unsafe {
                write!(f, "{}", (*current_node.as_ptr()).element).unwrap();
            }
            for _ in 0..self.len {
                unsafe {
                    match (*current_node.as_ptr()).next {
                        Some(node) => {
                            write!(f, "->{}", (*node.as_ptr()).element).unwrap();
                            current_node = node;
                        }
                        None => {
                            break;
                        }
                    }
                }
            }
        }
        return Ok(());
    }
}
#[cfg(not(feature = "no_std"))]
impl<T> Drop for LinkedList<T> {
    fn drop(&mut self) {
        // Pop items until there are none left
        while self.pop_front().is_some() {}
    }
}
#[cfg(not(feature = "no_std"))]
impl<T, const N: usize> From<[T; N]> for LinkedList<T> {
    fn from(array: [T; N]) -> Self {
        let mut new_linkedlist = LinkedList::new();
        for value in array {
            new_linkedlist.push_back(value);
        }
        return new_linkedlist;
    }
}

/// 将两个链表相加 每个节点为0-9
/// ```
/// use algori::structure::LinkedList;
/// use algori::structure::linkedlist::add_two_linkedlist;
/// let a: LinkedList<i32> = [1,3,2,5,5,2].into();
/// let b: LinkedList<i32> = [2,3,1,9,1,4,6,8].into();
/// assert_eq!(&add_two_linkedlist(a,b).to_vec(),&[3,6,3,4,7,6,6,8]);
/// ```
#[cfg(not(feature = "no_std"))]
pub fn add_two_linkedlist(a: LinkedList<i32>, b: LinkedList<i32>) -> LinkedList<i32> {
    let mut result = LinkedList::new();
    let current = &mut result;
    let (mut p1, mut p2) = (a, b);
    let mut sum = 0i32;
    while p1.front().is_some() || p2.front().is_some() || sum != 0 {
        if let Some(value) = p1.pop_front() {
            sum += value;
        }
        if let Some(value) = p2.pop_front() {
            sum += value;
        }
        current.push_back(sum % 10);
        sum = sum / 10;
    }
    return result;
}

/// 将两个链表相加 每个节点为二进制
/// ```
/// use algori::structure::LinkedList;
/// use algori::structure::linkedlist::add_two_binary_linkedlist;
/// let a: LinkedList<bool> = [true,false,true,false,false,false].into();
/// let b: LinkedList<bool> = [true,false,false,false,true].into();
/// assert_eq!(&add_two_binary_linkedlist(a,b).to_vec(),&[false,true,true,false,true,false]);
/// ```
#[cfg(not(feature = "no_std"))]
pub fn add_two_binary_linkedlist(a: LinkedList<bool>, b: LinkedList<bool>) -> LinkedList<bool> {
    let mut result = LinkedList::new();
    let (mut p1, mut p2) = (a, b);
    // sum[0]为第一个链表的值 sum[1]为第二个链表的值 sum[2]为上次进位
    let mut sum = [false; 3];
    while p1.front().is_some() || p2.front().is_some() || sum[2] == true {
        if let Some(value) = p1.pop_front() {
            sum[0] = value;
        }
        if let Some(value) = p2.pop_front() {
            sum[1] = value;
        }
        // 第一个链表和第二个链表的奇数判断[异或门]
        let xor1 = sum[0] ^ sum[1];

        // 全加器
        let add_result = xor1 ^ sum[2]; // sum的奇数判断[三路异或门]
        sum[2] = (xor1 & sum[2]) | (sum[0] & sum[1]); // 计算偶数进位[两个与门和一个或门]
        (sum[0], sum[1]) = (false, false); // 清零
        result.push_back(add_result);
    }

    return result;
}
#[cfg(not(feature = "no_std"))]
#[cfg(test)]
mod add_two_binary_test {
    use super::add_two_binary_linkedlist;
    use super::LinkedList;
    #[test]
    fn empty() -> () {
        let a: LinkedList<bool> = [].into();
        let b: LinkedList<bool> = [].into();
        let result = add_two_binary_linkedlist(a, b);
        assert_eq!(&result.to_vec(), &[]);
    }
    #[test]
    fn carry() -> () {
        let a: LinkedList<bool> = [true].into();
        let b: LinkedList<bool> = [true].into();
        let result = add_two_binary_linkedlist(a, b);
        assert_eq!(&result.to_vec(), &[false, true]);
    }
    #[test]
    fn one() -> () {
        let a: LinkedList<bool> = [false].into();
        let b: LinkedList<bool> = [true].into();
        let result = add_two_binary_linkedlist(a, b);
        assert_eq!(&result.to_vec(), &[true]);
    }
    #[test]
    fn two() -> () {
        let a: LinkedList<bool> = [true, false].into();
        let b: LinkedList<bool> = [true].into();
        let result = add_two_binary_linkedlist(a, b);
        assert_eq!(&result.to_vec(), &[false, true]);
    }
    #[test]
    fn more() -> () {
        let a: LinkedList<bool> = [false, false].into();
        let b: LinkedList<bool> = [true].into();
        let result = add_two_binary_linkedlist(a, b);
        assert_eq!(&result.to_vec(), &[true, false]);
    }
    #[test]
    fn common() -> () {
        let a: LinkedList<bool> = [false, false, true, true, false, true].into();
        let b: LinkedList<bool> = [true, false, true, false, true, false, true, true].into();
        let result = add_two_binary_linkedlist(a, b);
        assert_eq!(
            &result.to_vec(),
            &[true, false, false, false, false, false, false, false, true]
        );
    }
}
#[cfg(not(feature = "no_std"))]
#[cfg(test)]
mod add_two_linkedlist {
    use super::add_two_linkedlist;
    use super::LinkedList;
    #[test]
    fn empty() -> () {
        let a: LinkedList<i32> = [].into();
        let b: LinkedList<i32> = [].into();
        let result = add_two_linkedlist(a, b);
        assert_eq!(&result.to_vec(), &[]);
    }
    #[test]
    fn carry() -> () {
        let a: LinkedList<i32> = [9].into();
        let b: LinkedList<i32> = [8].into();
        let result = add_two_linkedlist(a, b);
        assert_eq!(&result.to_vec(), &[7, 1]);
    }
    #[test]
    fn one() -> () {
        let a: LinkedList<i32> = [2].into();
        let b: LinkedList<i32> = [3].into();
        let result = add_two_linkedlist(a, b);
        assert_eq!(&result.to_vec(), &[5]);
    }
    #[test]
    fn two() -> () {
        let a: LinkedList<i32> = [9, 2].into();
        let b: LinkedList<i32> = [3, 9].into();
        let result = add_two_linkedlist(a, b);
        assert_eq!(&result.to_vec(), &[2, 2, 1]);
    }
    #[test]
    fn more() -> () {
        let a: LinkedList<i32> = [9, 2, 9, 2].into();
        let b: LinkedList<i32> = [3, 9].into();
        let result = add_two_linkedlist(a, b);
        assert_eq!(&result.to_vec(), &[2, 2, 0, 3]);
    }
    #[test]
    fn common() -> () {
        let a: LinkedList<i32> =
            [0, 2, 3, 1, 5, 3, 6, 2, 5, 8, 1, 8, 9, 2, 9, 5, 3, 5, 9, 0].into();
        let b: LinkedList<i32> =
            [8, 2, 3, 6, 2, 1, 6, 2, 9, 1, 5, 1, 6, 5, 8, 2, 3, 1, 5, 2].into();
        let result = add_two_linkedlist(a, b);
        assert_eq!(
            &result.to_vec(),
            &[8, 4, 6, 7, 7, 4, 2, 5, 4, 0, 7, 9, 5, 8, 7, 8, 6, 6, 4, 3]
        );
    }
}