forked from TheAlgorithms/Rust
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinked_list.rs
More file actions
167 lines (150 loc) · 4.4 KB
/
linked_list.rs
File metadata and controls
167 lines (150 loc) · 4.4 KB
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
use std::fmt::{self, Display, Formatter};
use std::marker::PhantomData;
use std::ptr::NonNull;
struct Node<T> {
val: T,
next: Option<NonNull<Node<T>>>,
prev: Option<NonNull<Node<T>>>,
}
impl<T> Node<T> {
fn new(t: T) -> Node<T> {
Node {
val: t,
prev: None,
next: None,
}
}
}
pub struct LinkedList<T> {
length: u32,
start: Option<NonNull<Node<T>>>,
end: Option<NonNull<Node<T>>>,
// Act like we own boxed nodes since we construct and leak them
marker: PhantomData<Box<Node<T>>>,
}
impl<T> Default for LinkedList<T> {
fn default() -> Self {
Self::new()
}
}
impl<T> LinkedList<T> {
pub fn new() -> Self {
Self {
length: 0,
start: None,
end: None,
marker: PhantomData,
}
}
pub fn add(&mut self, obj: T) {
let mut node = Box::new(Node::new(obj));
// Since we are adding node at the end, next will always be None
node.next = None;
node.prev = self.end;
// Get a pointer to node
let node_ptr = Some(unsafe { NonNull::new_unchecked(Box::into_raw(node)) });
match self.end {
// This is the case of empty list
None => self.start = node_ptr,
Some(end_ptr) => unsafe { (*end_ptr.as_ptr()).next = node_ptr },
}
self.end = node_ptr;
self.length += 1;
}
pub fn pop_front(&mut self) -> Option<T> {
// Safety: start_ptr points to a leaked boxed node managed by this list
// We reassign pointers that pointed to the start node
self.start.map(|start_ptr| unsafe {
let old_start = Box::from_raw(start_ptr.as_ptr());
match old_start.next {
Some(mut next_ptr) => next_ptr.as_mut().prev = None,
None => self.end = None,
}
self.start = old_start.next;
self.length -= 1;
old_start.val
})
}
pub fn get(&mut self, index: i32) -> Option<&T> {
self.get_ith_node(self.start, index)
}
fn get_ith_node(&mut self, node: Option<NonNull<Node<T>>>, index: i32) -> Option<&T> {
match node {
None => None,
Some(next_ptr) => match index {
0 => Some(unsafe { &(*next_ptr.as_ptr()).val }),
_ => self.get_ith_node(unsafe { (*next_ptr.as_ptr()).next }, index - 1),
},
}
}
}
impl<T> Drop for LinkedList<T> {
fn drop(&mut self) {
// Pop items until there are none left
while self.pop_front().is_some() {}
}
}
impl<T> Display for LinkedList<T>
where
T: Display,
{
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self.start {
Some(node) => write!(f, "{}", unsafe { node.as_ref() }),
None => Ok(()),
}
}
}
impl<T> Display for Node<T>
where
T: Display,
{
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self.next {
Some(node) => write!(f, "{}, {}", self.val, unsafe { node.as_ref() }),
None => write!(f, "{}", self.val),
}
}
}
#[cfg(test)]
mod tests {
use super::LinkedList;
#[test]
fn create_numeric_list() {
let mut list = LinkedList::<i32>::new();
list.add(1);
list.add(2);
list.add(3);
println!("Linked List is {}", list);
assert_eq!(3, list.length);
}
#[test]
fn create_string_list() {
let mut list_str = LinkedList::<String>::new();
list_str.add("A".to_string());
list_str.add("B".to_string());
list_str.add("C".to_string());
println!("Linked List is {}", list_str);
assert_eq!(3, list_str.length);
}
#[test]
fn get_by_index_in_numeric_list() {
let mut list = LinkedList::<i32>::new();
list.add(1);
list.add(2);
println!("Linked List is {}", list);
let retrived_item = list.get(1);
assert!(retrived_item.is_some());
assert_eq!(2 as i32, *retrived_item.unwrap());
}
#[test]
fn get_by_index_in_string_list() {
let mut list_str = LinkedList::<String>::new();
list_str.add("A".to_string());
list_str.add("B".to_string());
println!("Linked List is {}", list_str);
let retrived_item = list_str.get(1);
assert!(retrived_item.is_some());
assert_eq!("B", *retrived_item.unwrap());
}
}