-
Notifications
You must be signed in to change notification settings - Fork 20
/
sllist.rs
126 lines (116 loc) · 3.14 KB
/
sllist.rs
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
#![allow(clippy::many_single_char_names,clippy::explicit_counter_loop)]
use chapter01::interface::{Queue, Stack};
use std::cell::RefCell;
use std::rc::Rc;
type Link<T> = Option<Rc<RefCell<Node<T>>>>;
#[derive(Clone, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
pub struct SLList<T> {
head: Link<T>,
tail: Link<T>,
n: usize,
}
impl<T> Drop for SLList<T> {
fn drop(&mut self) {
while self.remove().is_some() {}
}
}
#[derive(Clone, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
struct Node<T> {
x: T,
next: Link<T>,
}
impl<T> Node<T> {
fn new(x: T) -> Rc<RefCell<Self>> {
Rc::new(RefCell::new(Self { x, next: None }))
}
}
impl<T> SLList<T> {
pub fn new() -> Self {
Self {
head: None,
tail: None,
n: 0,
}
}
pub fn size(&self) -> usize {
self.n
}
}
impl<T> Stack<T> for SLList<T> {
fn push(&mut self, x: T) {
let new = Node::new(x);
match self.head.take() {
Some(old) => new.borrow_mut().next = Some(old),
None => self.tail = Some(new.clone()),
}
self.n += 1;
self.head = Some(new);
}
fn pop(&mut self) -> Option<T> {
self.head.take().map(|old| {
if let Some(next) = old.borrow_mut().next.take() {
self.head = Some(next);
} else {
self.tail.take();
}
self.n -= 1;
Rc::try_unwrap(old).ok().unwrap().into_inner().x
})
}
}
impl<T> Queue<T> for SLList<T> {
fn add(&mut self, x: T) {
let new = Node::new(x);
match self.tail.take() {
Some(old) => old.borrow_mut().next = Some(new.clone()),
None => self.head = Some(new.clone()),
}
self.n += 1;
self.tail = Some(new);
}
fn remove(&mut self) -> Option<T> {
self.head.take().map(|old| {
if let Some(next) = old.borrow_mut().next.take() {
self.head = Some(next);
} else {
self.tail.take();
}
self.n -= 1;
Rc::try_unwrap(old).ok().unwrap().into_inner().x
})
}
}
#[cfg(test)]
mod test {
use super::SLList;
use chapter01::interface::{Queue, Stack};
#[test]
fn test_sllist() {
let mut sllist: SLList<char> = SLList::new();
for elem in "abcde".chars() {
sllist.add(elem);
}
sllist.add('x');
assert_eq!(sllist.remove(), Some('a'));
assert_eq!(sllist.pop(), Some('b'));
sllist.push('y');
println!("\nSLList = {:?}", sllist);
for elem in "ycdex".chars() {
assert_eq!(sllist.remove(), Some(elem));
}
assert_eq!(sllist.pop(), None);
// test large linked list for stack overflow.
let mut sllist: SLList<i32> = SLList::new();
let num = 10;
for i in 0..num {
sllist.add(i);
}
while sllist.remove().is_some() {}
let mut sllist: SLList<i32> = SLList::new();
let num = 100000;
for i in 0..num {
sllist.add(i);
}
println!("fin");
}
}