zoukankan      html  css  js  c++  java
  • [LeetCode] Remove Duplicates from Sorted List II

    Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

    For example,
    Given 1->2->3->3->4->4->5, return 1->2->5.
    Given 1->1->1->2->3, return 2->3.

    关键是记录三个指针,当前指针p, p的父亲pPre, pPre的父亲pPrePre。

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode *deleteDuplicates(ListNode *head) {
    12         // Start typing your C/C++ solution below
    13         // DO NOT write int main() function
    14         if (head == NULL)
    15             return NULL;
    16         
    17         ListNode *pPrePre = NULL;    
    18         ListNode *pPre = NULL;
    19         ListNode *p = head;
    20         int key = INT_MAX;
    21         
    22         while(p)
    23         {
    24             if (key != p->val)
    25             {
    26                 key = p->val;
    27                 pPrePre = pPre;
    28                 pPre = p;
    29                 p = p->next;
    30             }
    31             else
    32             {
    33                 if (pPre && pPre->val == key)
    34                 {
    35                     ListNode *pNext = p->next;
    36                     if (pPrePre)
    37                         pPrePre->next = pNext;
    38                     if (head == pPre)
    39                         head = pNext;                   
    40                     delete pPre;
    41                     delete p;
    42                     pPre = pPrePre;
    43                     p = pNext;                       
    44                 }
    45                 else
    46                 {
    47                     ListNode *pNext = p->next;
    48                     if (pPre)
    49                         pPre->next = pNext;
    50                     if (head == p)
    51                         head = pNext;
    52                     delete p;
    53                     p = pNext;
    54                 }
    55             }
    56         }
    57         
    58         return head;
    59     }
    60 };
  • 相关阅读:
    MySQL 如何只导出 指定的表 的表结构和数据 ( 转 )
    速度之王 — LZ4压缩算法(三)
    lz4,pigz,gzip 3者比较
    用php实现百度网盘图片直链的代码分享
    hibernate的oracle配置(转)
    过滤器
    dom4j创建格式化的xml文件
    jstl表达式
    jsp内置对象和el表达式
    jsp 三大指令和动作标签
  • 原文地址:https://www.cnblogs.com/chkkch/p/2777344.html
Copyright © 2011-2022 走看看