• 83.删除排序链表中重复的结点


    题目描述:给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
    示例 1:
    输入: 1->1->2
    输出: 1->2

    • 双指针遍历:使用两个指针分别指向当前结点和当前结点的前一个结点,方便删除操作
    //C
    
    struct ListNode* deleteDuplicates(struct ListNode* head){
        //注意这里对head是否为空的判断
        if(head == NULL || head -> next == NULL) return head;
        struct ListNode *pre, *cur;
        pre = head;
        cur = head -> next;
        while(cur != NULL){
            if(pre -> val == cur -> val){
                struct ListNode *p;
                pre -> next = cur -> next;
                p = cur;
                free(p);
                cur = pre -> next;
            }
            else{
                pre = pre -> next;
                cur = cur -> next;
            }
        }
        return head;
    }
    • 单指针遍历:
    //JS
    
    var deleteDuplicates = function(head) {
        let cur = head;
        while(cur && cur.next){
            if(cur.val == cur.next.val){
                cur.next = cur.next.next;
            }
            else{
                cur = cur.next;
            }
        }
        return head;
    };
    • 哈希表或者Map记录出现过的结点元素:这里新建了一个头结点,方便遍历
    //JS
    
    var deleteDuplicates = function(head) {
        let hash = new Map(), p = head;
        let Lhead = new ListNode();
        let q = Lhead;
        Lhead.next = head;
    
        while(p){
            if(hash.has(p.val)) {
                q.next = p.next;
            }     
            else {
                hash.set(p.val, 1);  
                q = q.next;
            }
            p = p.next;
        }
        p = Lhead.next;
        Lhead = null;
        return p;
    };
    

      

  • 相关阅读:
    Codeforces Round #475 (Div. 1) B. Destruction of a Tree
    HDU
    HihoCoder
    浅谈spfa几个优化
    Codeforces Round #474 E. Alternating Tree
    Wannafly 挑战赛12 D
    2017 Multi-University Training Contest
    2017 Multi-University Training Contest
    斜率优化DP基础XVI Open Cup named after E.V. Pankratiev. GP of Ukraine.K
    斜率优化DP入门_HDU3507_Print Article
  • 原文地址:https://www.cnblogs.com/JesseyWang/p/13097519.html
Copyright © 2020-2023  润新知