给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:输入: 1->1->2->3->3
输出: 1->2->3
C++实现
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode * cur = head;
while (cur && cur->next)
{
if (cur->val == cur->next->val) {
cur->next = cur->next->next;
}
else{
cur = cur->next;
}
}
return head;
}
};
Rust实现
struct Solution{}
#[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 {
ListNode { next: None, val }
}
}
impl Solution {
pub fn delete_duplicates(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut head = head;
let mut cur = head.as_mut();
while cur.is_some() && cur.as_ref().unwrap().next.is_some() {
if cur.as_ref().unwrap().val == cur.as_ref().unwrap().next.as_ref().unwrap().val
{
let next = cur.as_mut().unwrap().next.as_mut().unwrap().next.take();
cur.as_mut().unwrap().next = next;
} else {
cur = cur.unwrap().next.as_mut();
}
}
head
}
}
结果