力扣 83. 删除排序链表中的重复元素(2015年408真题数据结构)

98 阅读1分钟

时间复杂度 O(n)O(n),空间复杂度 O(1)O(1)

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(head == nullptr) return head;
        ListNode *last = head, *now = head -> next;
        while(now != nullptr) {
            if(now -> val == last -> val) {
                last -> next = now -> next;
                now = last -> next;
            }
            else {
                last = now;
                now = now -> next;
            }
        }
        return head;
    }
};