Question number: 83 Delete duplicate elements in sorted linked list
Given a sorted linked list, remove all duplicate elements so that each element occurs only once
Example:
Input: 1->1->2
Output: 1->2
Problem-solving idea: define a middle layer, compare the data in the node with the middle layer, if the value is the same, assign the value to the middle layer, the node uses the pointer of the current middle layer, otherwise it directly accesses the next layer
struct ListNode{ int val; struct ListNode *next; } struct ListNode *deleteDuplictes(struct ListNode *head) { if(NULL==head){ return NULL; } //Security check, if the head node is NULL if(NULL==head->next) { return head; } //If the next node is NULL, return the head node struct ListNode *p=head; struct ListNode *pre=NULL; while(NULL!=p) { if(pre!=NULL&&pre->val==p->val){ //The conditional setting in the parentheses is very critical (pre!=NULL) and cannot be placed on the right side, which will cause "member access in the null pointer, while the linked list" The use of middle nodes is stricter than other data structures, and it must be ensured that the nodes used cannot be NULL, and deal with NULL accordingly") pre->next=p->next; p=pre->next; } } }