Given the head of a sorted linked list head
, remove all nodes with duplicate numbers in the original linked list, leaving only the different numbers . Returns a sorted linked list .
Idea 1: simulate the meaning of the question
struct ListNode* deleteDuplicates(struct ListNode* head){
if (head == NULL || head->next == NULL) return head;
struct ListNode nhead = {NULL, 0};
struct ListNode* p1 = head;
struct ListNode* p2 = &nhead;
int n,value;
while (p1) {
struct ListNode* tmp = p1;
for (n = 0,value = p1->val; p1 != NULL && p1->val == value; ++n)
p1 = p1->next;
if (n == 1) {
p2->next = tmp;
p2 = tmp;
}
}
p2->next = NULL;
return nhead.next;
}
analyze:
In this question, all duplicate elements will be deleted. You can consider creating a new linked list. If there are duplicate elements, do not put them into the new linked list, and finally output the new linked list. The linked list operation needs to use another linked list to record the original position. When n==1, make p2 point to tmp, and finally output nhead
Summarize:
This question examines the deletion operation of the linked list, that is, to judge whether the element is repeated, if it is repeated, it will not be put into the new linked list, and finally return