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

    class Solution {
    public:
        ListNode *deleteDuplicates(ListNode *head) {
            if (head == NULL) return NULL;
            ListNode *pre, *cur, *tmp;
            pre = head;
            cur = head->next;
            while (cur != NULL) {
                if (pre->val == cur->val) { // dup found
                    tmp = cur;
                    cur = tmp->next;
                    pre->next = tmp->next;
                    delete tmp;
                } else {
                    pre = cur;
                    cur = pre->next;
                }
            }
            return head;
        }
    };

    水一发

    第二轮:

    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.

     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  // 9:54
    10 class Solution {
    11 public:
    12     ListNode *deleteDuplicates(ListNode *head) {
    13         if (head == NULL) {
    14             return NULL;
    15         }
    16         ListNode* last = head;
    17         ListNode* cur = head->next;
    18         ListNode* pre = head;
    19         while (cur != NULL) {
    20             if (cur->val != pre->val) {
    21                 last->next = cur;
    22                 last = cur;
    23             }
    24             pre = cur;
    25             cur = cur->next;
    26         }
    27         last->next = NULL;
    28         return head;
    29     }
    30 };

     对比了一下原来还有delete

  • 相关阅读:
    13_函数的基本使用简介
    12_goto语句的使用
    11_for语句的使用
    10_switch语句的使用
    09_if条件语句的使用
    08_类型别名(类型声明)
    day-32网络编程
    day-31网络编程
    day-30网络编程
    day-29元类、异常处理
  • 原文地址:https://www.cnblogs.com/lailailai/p/3671687.html
Copyright © 2011-2022 走看看