删除掉所有的重复节点,遍历寻找时分两种情况:
相邻两个节点不同,即crt和crt->next的值不同重复节点有多个时,要用while不断寻找到不重复的节点。需要注意的是while内是否有可能访问空指针,需要在条件中判断是否为空 /** * Definition of singly-linked-list: * class ListNode { * public: * int val; * ListNode *next; * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */ class Solution { public: /** * @param head: head is the head of the linked list * @return: head of the linked list */ ListNode * deleteDuplicates(ListNode * head) { if (head == NULL || head->next == NULL) { return head; } ListNode *dummy = new ListNode(-1); dummy->next = head; ListNode *prev = dummy; ListNode *crt = head; while (crt != NULL && crt->next != NULL) { if(crt->val != crt->next->val) { prev = crt; crt = crt->next; } else { while (crt->next != NULL && crt->val == crt->next->val) { crt = crt->next; } prev->next = crt->next; crt = crt->next; } } return dummy->next; } };