其他分享
首页 > 其他分享> > Day2:Leetcode-83.Remove Duplicates from Sorted List

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

 

 

标签:pre,head,ListNode,cur,val,Duplicates,List,Day2,next
来源: https://blog.csdn.net/qq_39679069/article/details/120383834