删除排序链表中的重复元素 II

删除排序链表中的重复元素 II

CategoryDifficultyLikesDislikes
algorithmsMedium (45.93%)221-

Tags

linked-list

Companies

Unknown

给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 *没有重复出现 *的数字。

示例 1:

1
2
输入: 1->2->3->3->4->4->5
输出: 1->2->5

示例 2:

1
2
输入: 1->1->1->2->3
输出: 2->3

Discussion | Solution

解法

Rust

 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
impl Solution {
    pub fn delete_duplicates(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
        let mut dummy_head = Some(Box::new(ListNode::new(0)));
        let mut ptr = &mut dummy_head;

        let mut pre_val: i32 = -1;
        let mut pre_val_init = false;
        let mut next_val: i32 = 0;
        let mut head = head;
        while let Some(mut node) = head {
            head = node.next.take();
            if head.is_some() {
                if node.val == head.as_ref().unwrap().val {
                    pre_val_init = true;
                    pre_val = node.val;
                    continue
                }
            }
            if pre_val_init && pre_val == node.val {
                continue
            }
            pre_val = node.val;
            pre_val_init = true;
            ptr.as_mut().unwrap().next = Some(node);
            ptr = &mut ptr.as_mut().unwrap().next;
        }

        dummy_head.unwrap().next

    }
}
updatedupdated2024-08-252024-08-25