题解 | #删除有序链表中重复的元素-I#
删除有序链表中重复的元素-I
https://www.nowcoder.com/practice/c087914fae584da886a0091e877f2c79
双指针解法
当前指针和next指针比较val,
相等则当前指针指向后两位,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;
ListNode* next = head->next;
//迭代
while(next){
if(cur->val == next->val){
cur->next = next->next;
if(next->next){
next = next->next;
}else{
break;
}
}else{
cur = next;
next = next->next;
}
}
return head;
}
};