zoukankan      html  css  js  c++  java
  • Leetcode: 83. Remove Duplicates from Sorted List

    Description

    Given a sorted linked list, delete all duplicates such that each element appear only once.

    Example

    Given 1->1->2, return 1->2.
    Given 1->1->2->3->3, return 1->2->3.
    

    思路

    • 链表去重,一旦重复,留下一个节点

    代码

    /**
     * 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) {
            if(!head) return NULL;
            ListNode *ptr = head, *pNext = head->next;
            ListNode *res = new ListNode(0);
            ListNode *h = res;
            
            while(pNext){
                if(ptr->val == pNext->val){
                    do{
                        ListNode *tmp = pNext;
                        pNext = pNext->next;
                        delete tmp;
                    }while(pNext && pNext->val == ptr->val);
                }
                
                res->next = ptr;
                res = res->next;
                ptr = pNext;
                if(ptr)
                    pNext = ptr->next;
            }
            
            if(ptr && res && res->val != ptr->val){
                res->next = ptr;
                res = res->next;
            }
            
            res->next = NULL;
            return h->next;
        }
    };
    
  • 相关阅读:
    网页中的JavaScript
    css颜色表示
    css文本属性
    css2选择器
    css3选择器
    Canvas练习
    Canvas
    CSS样式之语法
    css基础1
    php操作成功返回当前页并刷新
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6953917.html
Copyright © 2011-2022 走看看