题解 | #删除有序链表中重复的元素-I#
删除有序链表中重复的元素-I
https://www.nowcoder.com/practice/c087914fae584da886a0091e877f2c79
1.还是边界条件非常难考虑,特别容易出现数组越界的情况发生
2.当前节点的值与后续节点的值不匹配时,那么此时当前节点位置保持不变,删除重复节点,然后与下一个节点连接
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @return ListNode类
*/
ListNode* deleteDuplicates(ListNode* head) {
// write code here
//删除有序链表的重复元素
if(head == nullptr || head->next == nullptr) return head;
ListNode* cur = head;
while(cur != nullptr && cur->next != nullptr)
{
//保留cur
ListNode* temp = cur->next;
ListNode* next;
if(cur->next != nullptr)
{
next = cur->next->next;
}
else
{
next = nullptr;
}
if(temp->val == cur->val)
{
delete temp;
cur->next = next;
//cur = next;
}
//只有在与之不匹配时才会继续进行下一步
else
{
cur = cur->next;
}
}
return head;
}
};

查看7道真题和解析