LeetCode 面試題 02.01. 移除重複節點 (哈希表、鏈表節點的刪除、內存的釋放)

移除重複節點

/**
 * 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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章