【Leetcode083】Remove Duplicates from Sorted List

/**
 * 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才发现的。

发布了112 篇原创文章 · 获赞 15 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_39458342/article/details/103413037