移除链表的重复节点(简单题)

在这里插入图片描述
哈希+双指针,很轻松的小题。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeDuplicateNodes(ListNode* head) {
        if(head==NULL)return NULL;
        unordered_set<int>myset={head->val};
        ListNode*prev=head;
        ListNode*cur=head->next;
        while(cur!=NULL)
        {
            if(myset.find(cur->val)==myset.end())
            {
                myset.insert(cur->val);
                prev=cur;
                cur=cur->next;
            }
            else
            {
                prev->next=cur->next;
                cur=cur->next;
            }
        }
        return head;

    }
};

猜你喜欢

转载自blog.csdn.net/ShenHang_/article/details/106976659