欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 面试题 02.01. 移除重复节点 (哈希表、链表节点的删除、内存的释放)

程序员文章站 2022-05-20 19:05:45
...

移除重复节点

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool vis[20010] = {0};
    ListNode* removeDuplicateNodes(ListNode* head) {
        if(!head){
            return nullptr;
        }
        ListNode *pre=nullptr,*cur=nullptr;
        vis[head->val] = 1;
        pre = head;
        cur = head->next;
        while(cur){
            bool flag = false;
            if(vis[cur->val]){
                pre->next = cur->next;
                flag = true;
            }else{
                pre = cur;
            }
            vis[cur->val] = 1;
            ListNode* toDelete = cur;
            cur = cur->next;
            if(flag){
                delete toDelete ;
            }
        }
        return head;
    }
};
相关标签: LeetCode # LC链表