zoukankan      html  css  js  c++  java
  • LeetCode OJ:Remove Duplicates from Sorted List II(链表去重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.

    这里对于链表去重是要将有重复的链表节点全部都去掉,一个都不能留,思路还是比较简单的,跟前面的I那一题实际上差不多,代码如下所示:

     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         if(!head) return NULL;
    13         ListNode * helper = new ListNode(INT_MAX);
    14         helper->next = head;
    15         ListNode * prev = helper;
    16         ListNode * curr = head;
    17         while(curr){
    18             if(curr->next && curr->val == curr->next->val){
    19                 ListNode * tmpNode = curr->next;
    20                 while(tmpNode->next && curr->val == tmpNode->next->val){
    21                     tmpNode = tmpNode->next;
    22                 }
    23                 prev->next = tmpNode->next;
    24                 curr = prev->next;
    25             }else{
    26                 prev = curr;
    27                 curr = curr->next;
    28             }
    29         }
    30         return helper->next;
    31     }
    32 };
  • 相关阅读:
    串口通信
    无法安装SQL提示文件被挂起
    flash图片幻灯片浏览
    document.all与WEB标准
    在新窗口中打开页面 的asp.net后台代码
    sql 触发器
    无技术含量的正则表达式笔记
    两个FTP服务器之间传送数据
    repeater嵌套
    登录
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/5005052.html
Copyright © 2011-2022 走看看