Skip to content

Commit 32da18f

Browse files
committed
Basic linked list
0 parents  commit 32da18f

File tree

4 files changed

+83
-0
lines changed

4 files changed

+83
-0
lines changed

Diff for: .gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
/target

Diff for: Cargo.lock

+7
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Diff for: Cargo.toml

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
[package]
2+
name = "linked-list"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7+
8+
[dependencies]

Diff for: src/main.rs

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
// Define a basic Node structure
2+
struct Node<T> {
3+
value: T,
4+
next: Option<Box<Node<T>>>,
5+
}
6+
7+
// Define a LinkedList structure
8+
pub struct LinkedList<T> {
9+
head: Option<Box<Node<T>>>,
10+
}
11+
12+
impl<T> LinkedList<T> {
13+
// Create a new empty linked list
14+
pub fn new() -> Self {
15+
LinkedList { head: None }
16+
}
17+
18+
// Add an element to the front of the linked list
19+
pub fn push(&mut self, value: T) {
20+
let new_node = Box::new(Node {
21+
value,
22+
next: self.head.take(),
23+
});
24+
self.head = Some(new_node);
25+
}
26+
27+
// Remove and return the element from the front of the linked list
28+
pub fn pop(&mut self) -> Option<T> {
29+
self.head.take().map(|node| {
30+
self.head = node.next;
31+
node.value
32+
})
33+
}
34+
35+
// Check if the linked list is empty
36+
pub fn is_empty(&self) -> bool {
37+
self.head.is_none()
38+
}
39+
40+
// Get the length of the linked list
41+
pub fn len(&self) -> usize {
42+
let mut current = &self.head;
43+
let mut count = 0;
44+
while let Some(node) = current {
45+
count += 1;
46+
current = &node.next;
47+
}
48+
count
49+
}
50+
}
51+
52+
53+
fn main() {
54+
let mut list = LinkedList::new();
55+
56+
list.push(1);
57+
list.push(2);
58+
list.push(3);
59+
60+
println!("Length of the linked list: {}", list.len());
61+
62+
while let Some(value) = list.pop() {
63+
println!("Popped value: {}", value);
64+
}
65+
66+
println!("Is the linked list empty? {}", list.is_empty());
67+
}

0 commit comments

Comments
 (0)