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

    Given a sorted linked list, delete all duplicates such that each element appear only once.

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

    顺序扫描一遍即可,注意释放被删除的结点的空间。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *deleteDuplicates(ListNode *head) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            if(head == NULL)
                return NULL;
                
            ListNode *last = head, *current = head -> next, *tmp = NULL;
            while(current != NULL)
            {
                while(current != NULL && current -> val == last -> val)
                {
                    tmp = current;
                    current = current -> next;
                    delete tmp;
                }
                
                last -> next = current;
                last = current;
                
                if(current != NULL)
                    current = current -> next;
            }
            
            return head;
        }
    };
  • 相关阅读:
    108.异常的传递
    107.捕获异常
    106.异常、模块(异常介绍)
    105.面向对象案例-烤红薯
    104.多态案例
    103.继承案例二
    102.继承案例一
    101.自定义玩家类
    100.自定义枪类
    python基础入门之十四 —— 文件操作
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3415546.html
Copyright © 2011-2022 走看看