ListNode struct is now in its own module linked_list, added list! macro for easier linked list creations, added tests for p2 and p19

This commit is contained in:
Egor 2024-05-02 10:59:40 +03:00
parent 4e4fad9311
commit 8ccc50e6ee
4 changed files with 70 additions and 17 deletions

View file

@ -1,3 +1,5 @@
#[macro_use]
pub mod linked_list;
pub mod p1_two_sum;
pub mod p2_add_two_numbers;
pub mod p3_longest_substring_without_repeating_characters;
@ -16,3 +18,4 @@ pub mod p15_3sum;
pub mod p16_3sum_closest;
pub mod p17_letter_combinations_of_a_phone_number;
pub mod p18_4sum;
pub mod p19_remove_nth_node_from_end_of_list;

32
src/linked_list.rs Normal file
View file

@ -0,0 +1,32 @@
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>
}
impl ListNode {
#[inline]
pub fn new(val: i32) -> Self {
Self { next: None, val }
}
}
#[macro_export]
macro_rules! list {
() => { None };
( $first:expr ) => { Some(Box::new(ListNode::new($first))) };
( $first:expr, $($x:expr),* ) => {
{
let mut head = Box::new(ListNode::new($first));
let mut tail = &mut head;
#[allow(unused_assignments)]
{
$(
tail.next = Some(Box::new(ListNode::new($x)));
tail = tail.next.as_mut().unwrap();
)*
}
Some(head)
}
};
}

View file

@ -0,0 +1,23 @@
use super::linked_list::ListNode;
struct Solution;
impl Solution {
pub fn remove_nth_from_end(head: Option<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> {
return None;
}
}
#[test]
fn test1() {
assert_eq!(Solution::remove_nth_from_end(list![1,2,3,4,5], 2), list![1,2,3,5]);
}
#[test]
fn test2() {
assert_eq!(Solution::remove_nth_from_end(list![1], 1), list![]);
}
#[test]
fn test3() {
assert_eq!(Solution::remove_nth_from_end(list![1,2], 1), list![1]);
}

View file

@ -1,3 +1,5 @@
use super::linked_list::ListNode;
pub struct Solution;
impl Solution {
pub fn add_two_numbers(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
@ -27,24 +29,17 @@ impl Solution {
}
}
// Definition for singly-linked list.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>
}
impl ListNode {
#[inline]
fn new(val: i32) -> Self {
ListNode {
next: None,
val
}
}
#[test]
fn test1() {
assert_eq!(Solution::add_two_numbers(list![2,4,3], list![5,6,4]), list![7,0,8]);
}
#[test]
fn test() {
fn test2() {
assert_eq!(Solution::add_two_numbers(list![0], list![0]), list![0]);
}
#[test]
fn test3() {
assert_eq!(Solution::add_two_numbers(list![9,9,9,9,9,9,9], list![9,9,9,9]), list![8,9,9,9,0,0,0,1]);
}