Skip to content

Commit

Permalink
leetcode: Add remove duplicates from sorted list
Browse files Browse the repository at this point in the history
  • Loading branch information
XuShaohua committed Dec 5, 2023
1 parent d02295d commit fe5be6f
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 0 deletions.
4 changes: 4 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions leetcode/0083.remove-duplicates-from-sorted-list/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "lc-0083-remove-duplicates-from-sorted-list"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
80 changes: 80 additions & 0 deletions leetcode/0083.remove-duplicates-from-sorted-list/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// Copyright (c) 2023 Xu Shaohua <[email protected]>. All rights reserved.
// Use of this source is governed by General Public License that can be
// found in the LICENSE file.

#![allow(dead_code)]

#[derive(Debug, Clone, PartialEq, Eq)]
struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}

impl ListNode {
#[inline]
#[must_use]
pub const fn new(val: i32) -> Self {
Self { val, next: None }
}

pub fn from_slice(slice: &[i32]) -> Option<Box<Self>> {
let mut list = None;
for item in slice.iter().rev() {
list = Self::cat(list, *item);
}
list
}

pub fn cat(list: Option<Box<Self>>, val: i32) -> Option<Box<Self>> {
Some(Box::new(Self { val, next: list }))
}
}

fn solution1(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
if let Some(head) = head {
let val = head.val;
if let Some(next) = head.next {
if next.val == val {
ListNode::cat(solution1(next.next), val)
} else {
ListNode::cat(solution1(Some(next)), val)
}
} else {
Some(head)
}
} else {
None
}
}

fn main() {
let list = ListNode::from_slice(&[1, 1, 2]);
let result = solution1(list);
println!("result: {result:?}");
let expected_result = ListNode::from_slice(&[1, 2]);
assert_eq!(result, expected_result);

let list = ListNode::from_slice(&[1, 1, 2, 3, 3]);
let result = solution1(list);
println!("result: {result:?}");
let expected_result = ListNode::from_slice(&[1, 2, 3]);
assert_eq!(result, expected_result);
}

#[cfg(test)]
mod tests {
use super::{solution1, ListNode};

#[test]
fn test_solution1() {
let list = ListNode::from_slice(&[1, 1, 2]);
let result = solution1(list);
let expected_result = ListNode::from_slice(&[1, 2]);
assert_eq!(result, expected_result);

let list = ListNode::from_slice(&[1, 1, 2, 3, 3]);
let result = solution1(list);
let expected_result = ListNode::from_slice(&[1, 2, 3]);
assert_eq!(result, expected_result);
}
}

0 comments on commit fe5be6f

Please sign in to comment.