/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head == NULL) return NULL;//空返回NULL
ListNode* current = head;
while(current -> next != NULL){ //大于1个,判断是否相等;如果最后一个,不用再往后判断了
if(current->val != current->next->val)
current = current->next;
else
current->next = current->next->next;
}
return head;
}
};
用指针从head开始去重,最终返回head,因为head不会去掉。
坑爹之处在于元素可能为0个,需要直接返回NULL,这种特殊情况。
另外要特别注意判断是否相等“==“,别用成了"=",debug才发现的。