Given the head
of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Example 1:
Input: head = [1,1,2] Output: [1,2]
Example 2:
Input: head = [1,1,2,3,3] Output: [1,2,3]
Constraints:
- The number of nodes in the list is in the range
[0, 300]
. -100 <= Node.val <= 100
- The list is guaranteed to be sorted in ascending order.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(!head)return nullptr;
ListNode*dummyHead=head;
while(dummyHead->next!=NULL){
if(dummyHead->val==dummyHead->next->val){
dummyHead->next=dummyHead->next->next;
}else{
dummyHead=dummyHead->next;
}
}
return head;
}
};
注意:
1.需要先判断链表是否为空
2.因为需要直接在链表上进行删除操作,所以用dummyHead直接=head,之所以没有用Head直接操作,是为了return的时候方便找到最开始的Head位置。
标签:head,dummyHead,ListNode,val,Duplicates,list,Remove,next,83 From: https://blog.csdn.net/2301_80161204/article/details/139849043