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
use crate::AbsoluteLinkedList;
use crate::Num;
use num_traits::zero;
pub trait AbsoluteCircularLinkedList<T: Num>: AbsoluteLinkedList<T> {
fn attach_before(&mut self, base_element: T, new_element: T) {
let base_element_previous = self.get_previous(base_element);
self.set_previous(new_element, base_element_previous);
self.set_next(new_element, base_element);
if base_element == self.get_first() {
self.set_first(new_element);
}
self.set_next(base_element_previous, new_element);
self.set_previous(base_element, new_element);
self.inc_size();
}
fn attach_after(&mut self, base_element: T, new_element: T) {
let base_element_next = self.get_next(base_element);
self.set_previous(new_element, base_element);
self.set_next(new_element, base_element_next);
if base_element == self.get_last() {
self.set_last(new_element);
}
self.set_previous(base_element_next, new_element);
self.set_next(base_element, new_element);
self.inc_size();
}
fn attach_as_first(&mut self, element: T) {
let first = self.get_first();
if first == zero() {
self.set_first(element);
self.set_last(element);
self.set_previous(element, element);
self.set_next(element, element);
self.inc_size();
} else {
self.attach_before(first, element);
}
}
fn attach_as_last(&mut self, element: T) {
let last = self.get_last();
if last == zero() {
self.attach_as_first(element);
} else {
self.attach_after(last, element);
}
}
fn detach(&mut self, element: T) {
let element_previous = self.get_previous(element);
let element_next = self.get_next(element);
if element_next == element {
self.set_first(zero());
self.set_last(zero());
} else {
self.set_next(element_previous, element_next);
self.set_previous(element_next, element_previous);
if element == self.get_first() {
self.set_first(element_next);
}
if element == self.get_last() {
self.set_last(element_previous);
}
}
self.set_previous(element, zero());
self.set_next(element, zero());
self.dec_size();
}
}