Day2:Leetcode-83.Remove Duplicates from Sorted List

Solution 1: 

It is a sorted linked list, we can delete all duplicates one by one,but at first I made a mistake in case [0,0,0,0,0] , because I set pre number 0,therefore I turn it to be -99,that is okay.

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
       ListNode *pre = new ListNode(-99,head);
       ListNode *cur = head;
       while(head){
         if(head->val == pre->val){
             pre->next = head->next;
             head = head->next;
         }else{
             pre = head;
             head = head->next;
         }
           
       }

        return cur;    
    }
};

 Python version

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        if not head:
            return head
        cur = head
        while cur.next:
            if cur.next.val == cur.val:
                cur.next = cur.next.next
                cur = cur.next
            else:
                cur = cur.next
        return head

 

 

上一篇:boost::hana::detail::has_duplicates用法的测试程序


下一篇:关于drop_duplicates的两种用法