Skip to content

Commit 896e95f

Browse files
committed
add 203
1 parent 3a7b737 commit 896e95f

File tree

3 files changed

+96
-0
lines changed

3 files changed

+96
-0
lines changed

S0203-remove-linked-list-elements/Cargo.lock

Lines changed: 4 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
[package]
2+
name = "S0203-remove-linked-list-elements"
3+
version = "0.1.0"
4+
authors = ["xargin <cao1988228@163.com>"]
5+
edition = "2018"
6+
7+
[dependencies]
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
fn main() {
2+
println!("Hello, world!");
3+
}
4+
5+
// Definition for singly-linked list.
6+
#[derive(PartialEq, Eq, Debug)]
7+
pub struct ListNode {
8+
pub val: i32,
9+
pub next: Option<Box<ListNode>>
10+
}
11+
12+
impl ListNode {
13+
#[inline]
14+
fn new(val: i32) -> Self {
15+
ListNode {
16+
next: None,
17+
val
18+
}
19+
}
20+
}
21+
22+
struct Solution;
23+
24+
impl Solution {
25+
pub fn remove_elements(mut head: Option<Box<ListNode>>, val: i32) -> Option<Box<ListNode>> {
26+
while head.is_some() && head.as_ref().unwrap().val == val {
27+
head = head.unwrap().next;
28+
}
29+
if head.is_none() {
30+
return head
31+
}
32+
33+
let mut cur = &mut head;
34+
while cur.as_ref().unwrap().next.is_some() {
35+
if cur.as_ref().unwrap().next.as_ref().unwrap().val == val {
36+
let next= std::mem::replace(&mut cur.as_mut().unwrap().next, None);
37+
std::mem::replace(&mut cur.as_mut().unwrap().next, next.unwrap().next);
38+
continue;
39+
}
40+
cur = &mut cur.as_mut().unwrap().next;
41+
}
42+
43+
return head;
44+
}
45+
}
46+
47+
/*
48+
use std::mem;
49+
impl Solution {
50+
pub fn remove_elements(mut head: Option<Box<ListNode>>, val: i32) -> Option<Box<ListNode>> {
51+
let mut cur = &mut head;
52+
while cur.is_some() {
53+
match cur.as_ref() {
54+
Some(node) if node.val == val => {
55+
let mut move_out = cur.take();
56+
mem::swap(cur, &mut move_out.as_mut().unwrap().next);
57+
continue;
58+
}
59+
_ => {}
60+
}
61+
cur = &mut cur.as_mut().unwrap().next;
62+
}
63+
head
64+
}
65+
}
66+
*/
67+
68+
/*
69+
这个很优雅
70+
impl Solution {
71+
pub fn remove_elements(head: Option<Box<ListNode>>, val: i32) -> Option<Box<ListNode>> {
72+
let mut dummy = ListNode{val:0, next:head};
73+
let mut p = &mut dummy;
74+
while let Some(q) = p.next.as_mut() {
75+
if q.val == val {
76+
p.next = q.next.take();
77+
}else{
78+
p = p.next.as_mut().unwrap();
79+
}
80+
}
81+
82+
dummy.next
83+
}
84+
}
85+
*/

0 commit comments

Comments
 (0)