My simple and easy understand C++ solution


  • 0
    W

    /**

    • 方法很简单,就是从头开始遍历,将不一样的元素拷贝到数组的前面,然后删除尾部多余的节点。

    *The idea is simple.Just check the item in the linked list and copy distinct item to the front place.
    *Finally, delete surplus nodes on the tail
    */

    class Solution {

    public:

    ListNode* deleteDuplicates(ListNode* head) {
        if (head==nullptr||head->next==nullptr) return head;
        ListNode* tmp=head;
        ListNode* tmp1=head->next;
        while(tmp1!=nullptr){
            if(tmp1->val!=tmp->val){
                tmp=tmp->next;
                tmp->val=tmp1->val;
            }
            tmp1=tmp1->next;
        }
        tmp->next=nullptr;
        return head;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.