给定的链表是排好序的,只要对链表进行一次遍历,就可以删除重复元素。我们从指针 cur 指向链表的头节点,开始对链表进行遍历,如果当前 cur .next与 cur.next.next 对应的元素相同,那么就将 cur.next .next从链表中移除,如果当前 cur.next 与 cur.next.next 对应的元素不相同,说明链表中只有一个元素值为 cur.next 的节点,就可以将 cur 指向 cur.next,当遍历完整个链表之后,返回链表的的哑节点的下一个节点 dummy.next
if (!head) {
return head;
}
ListNode* dummy = new ListNode(0, head);
ListNode* cur = dummy;
while (cur->next && cur->next->next) {
if (cur->next->val == cur->next->next->val) {
int x = cur->next->val;
while (cur->next && cur->next->val == x) {
cur->next = cur->next->next;
}
}
else {
cur = cur->next;
}
}
return dummy->next;
}
};