• 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 };
     
  • 相关阅读:
    微信公众平台开发(53)砸金蛋
    微信公众平台高级功能
    微信5.0安卓内测版下载
    微信公众平台2013.08.05更新说明
    淘宝微信互相屏蔽影响了谁
    WAP网页输入框的默认键盘类型控制
    如何通过微信创业赚钱
    腾讯风铃
    腾讯推出微信企业服务平台风铃
    一键生成HTML4和WAP站
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/5940212.html
Copyright © 2020-2023  润新知