Given the head of a sorted linked list head
, remove all duplicate elements such that each element appears only once . Returns a sorted linked list .
Input: head = [1,1,2] Output: [1,2]
Idea 1: simulate the meaning of the question
struct ListNode* deleteDuplicates(struct ListNode* head){
if(head==NULL||head->next==NULL)return head;
struct ListNode*p = head,*q = head->next;
while(q!=NULL)
{
if(p->val==q->val)p->next = q->next;
else{
p = p->next;
}
q = q->next;
}
return head;
}
analyze:
This question is similar to the previous question, but instead of deleting all repeated elements, many repeated elements can be deleted. You can add a judgment statement to judge whether the previous and next val values are equal to decide whether to put it into the linked list, and finally output the linked list
Summarize:
This question examines the delete operation of the linked list, and it can be made by adding a judgment statement.