Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e9475e4

Browse files
Added a Singly Linked List
1 parent 55c3948 commit e9475e4

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

‎src/utils/linked_lists.rs

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
#[cfg(feature = "serde")]
2+
use serde::{Deserialize, Serialize};
3+
/// ## Description
4+
///
5+
/// The struct works by having a value and an optional pointer to a next ListNode.
6+
/// When writing the nodes you need to start from the last one and make your way down to the first
7+
/// one.
8+
///
9+
/// The struct signature is entirely 1:1 with LeetCode with additional optional features like
10+
/// serde.
11+
///
12+
/// ## Example
13+
///
14+
/// ```rust
15+
/// use leetcode_trees_rs::utils::ListNode;
16+
/// use std::boxed::Box;
17+
/// use std::option::Option;
18+
///
19+
/// // Last node
20+
/// let node_3 = ListNode::new(7);
21+
///
22+
/// // Second node
23+
/// let node_2 = ListNode{
24+
/// val: 6,
25+
/// next: Some(Box::new(node_3)),
26+
/// };
27+
///
28+
/// // First node
29+
/// let node_1 = ListNode {
30+
/// val: 5,
31+
/// next: Some(Box::new(node_2)),
32+
/// };
33+
/// ```
34+
/// Result: 5 -> 6 -> 7 -> `None`
35+
///
36+
/// ## Big O
37+
///
38+
/// Peeking/modifying the first element -> O(1)
39+
/// Peeking/modifying the last element -> O(n)
40+
/// Removing the first element -> O(1)
41+
/// Removing any next element -> O(n)
42+
/// Adding a new element at the end -> O(n)
43+
/// Adding a new element at the start -> O(1)
44+
/// Searching -> O(n)
45+
#[derive(PartialEq, Eq, Clone, Debug)]
46+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
47+
pub struct ListNode {
48+
/// This uses normal i32 values that can be serialized and deserialized using serde if wanted.
49+
pub val: i32,
50+
51+
/// An optional box for a next ListNode.
52+
#[cfg_attr(feature = "serde", serde(skip))]
53+
pub next: Option<Box<ListNode>>,
54+
}
55+
56+
impl ListNode {
57+
/// Used to make a new ListNode with next as `None`.
58+
#[inline]
59+
pub fn new(val: i32) -> Self {
60+
ListNode { next: None, val }
61+
}
62+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /