zoukankan      html  css  js  c++  java
  • LeetCode82 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.(Medium)

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

    分析:

    链表去重的follow-up,但是题号这个在前面,要把有重复元素,则所有该元素均删掉。

    注意:

    1. 使用dummy node处理头结点被删除掉的情况。

    2. 只要有head-> next -> val存在时,先判断head -> next是否为空。

    代码:

     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         ListNode dummy(0);
    13         dummy.next = head;
    14         head = &dummy;
    15         while(head -> next != nullptr && head -> next -> next != nullptr) {
    16             if (head -> next -> val == head -> next -> next -> val) {
    17                 int val = head -> next -> val;
    18                 while (head -> next != nullptr && head -> next -> val == val) { //只要取head->next,先判断
    19                     ListNode* temp = head -> next;
    20                     head -> next = head -> next -> next;
    21                     delete temp;
    22                 }
    23             }
    24             else {
    25                 head = head -> next;
    26             }
    27         }
    28         return dummy.next;
    29     }
    30 };
     
  • 相关阅读:
    Infosec institute n00bs CTF writeup
    CTF学习之CODE
    ThinkPHP函数详解:C方法
    流程控制的替代语法
    Jquery DOM
    YII2 请求(request)
    YII2 运行概述(Overview)
    YII2 小部件(widgets)
    YII2 过滤器 filters
    YII2 随笔 视图最佳实践
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/5940212.html
Copyright © 2011-2022 走看看