leetcode No.83 remove sorts the list of repeating elements

topic

Link: https: //leetcode-cn.com/problems/remove-duplicates-from-sorted-list

Given a sorted list, delete all the duplicate elements, so that each element occurs only once.

Example 1:

Input: 1-> 1-> 2

Output: 1-> 2

Example 2:

Input: 1-> 1-> 2-> 3-> 3

Output: 1-> 2-> 3

C ++ code

/**
 * 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) {
        ListNode* p = head;
        while(p != NULL){
            ListNode* n = p->next;
            int dup_val = p->val;
            while(n != NULL && n->val == dup_val)
                n = n->next;
            p->next = n;
            p = n;
        }
        return head;
    }
};

When execution: 12ms, defeated 74.74% of all users to submit in C ++

Memory consumption: 13.2MB, beat the 5.06% of all users to submit in C ++

Python3 Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        p = head
        while(p != None):
            n = p.next
            dup_val = p.val
            while(n != None and n.val == dup_val):
                n = n.next
            p.next = n
            p = n
        return head
Published 98 original articles · won praise 353 · views 540 000 +

Guess you like

Origin blog.csdn.net/u011583927/article/details/104741970