-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrust-test.rs
57 lines (47 loc) · 1.25 KB
/
rust-test.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
// Define the struct for a Node in the list
struct Node<T> {
data: T,
next: Option<Box<Node<T>>>,
prev: Option<Box<Node<T>>>,
}
// Define the LinkedList struct
struct LinkedList<T> {
head: Option<Box<Node<T>>>,
tail: Option<Box<Node<T>>>,
}
// Implement LinkedList
impl<T> LinkedList<T> {
// Create a new empty list
fn new() -> Self {
LinkedList { head: None, tail: None }
}
// Push a new element to the front of the list
fn push(&mut self, data: T) {
let new_node = Box::new(Node {
data,
next: self.head.take(),
prev: None
});
self.head.prev = Some(new_node);
self.head = Some(new_node);
}
// Pop an element from the front of the list
fn pop(&mut self) -> Option<T> {
self.head.take().map(|node| {
self.head = node.next;
node.data
})
}
// Peek at the front element of the list, without removing it
fn peek(&self) -> Option<&T> {
self.head.as_ref().map(|node| &node.data)
}
}
fn main() {
let mut list = LinkedList::new();
list.push(1);
list.push(2);
list.push(3);
println!("{:?}", list.pop()); // Output: Some(3)
println!("{:?}", list.peek()); // Output: Some(&2)
}