-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathremove-linked-list-elements.rs
48 lines (38 loc) · 1.09 KB
/
remove-linked-list-elements.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#![allow(dead_code, unused, unused_variables)]
fn main() {}
struct 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 }
}
}
impl Solution {
pub fn remove_elements(head: Option<Box<ListNode>>, val: i32) -> Option<Box<ListNode>> {
if head.is_none() {
return head;
}
let mut head = head;
// 去掉前面都是满足值的节点
while head.is_some() && head.as_ref().unwrap().val == val {
head = head.as_mut().unwrap().next.take();
}
let mut cursor = head.as_mut();
while cursor.is_some() {
if let Some(i) = cursor.as_mut().unwrap().next.as_mut() {
if i.val == val {
cursor.as_mut().unwrap().next = i.next.take();
continue;
}
}
cursor = cursor.unwrap().next.as_mut();
}
head
}
}