• leetcode 82. 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.

    Example 1:

    Input: 1->2->3->3->4->4->5
    Output: 1->2->5
    

    Example 2:

    Input: 1->1->1->2->3
    Output: 2->3

    题目大意:给定已排序的链表,删除所有有重复数字的结点。

    c++:

     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 == nullptr) || (head->next == nullptr)) return head; //如果链表为空或者只有一个结点,直接返回
    13         ListNode *ans = new ListNode(0); //为方便后续操作,建立头结点
    14         ListNode *cur = ans; //cur指针指向结果链表的表尾
    15         ListNode *slow = head, *fast;
    16         while (slow != nullptr) {
    17             fast = slow->next;
    18             while (fast != nullptr && (fast->val == slow->val)) //只要fast不为空,并且其值和slow->val相等,那么fast往后移
    19                 fast = fast->next;
    20             if (slow->next == fast) { //slow指向fast,说明slow和fast相邻且值不相等,那么slow指向的结点可以并入结果链表中
    21                 cur->next = slow;
    22                 cur = slow;
    23                 cur->next = nullptr; //很关键,需要及时将结果链表和slow指向的head链表断开。
    24             }
    25             slow = fast; //不管前面slow是否指向fast,fast指向的结点都是下一个并入结果链表的候选结点。
    26             //cur->next = nullptr;
    27         }
    28         return ans->next;
    29     }
    30 };
  • 相关阅读:
    Resize a VMWare disk (zz)
    StepbyStep: Installing SQL Server Management Studio2008 Express after Visual Studio 2010(zz)
    (C#)利用反射动态调用类成员[转载]
    Discuz!NT 系统架构分析 (转)
    C#反射实例讲解(转)
    什么是反射?
    创建保存图片目录
    取资源文件中的值 System.Resources.ResourceManager
    Net中的反射使用入门
    iis上实现虚拟目录
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/12190779.html
Copyright © 2020-2023  润新知