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

  • 相关阅读:
    面向对象的思维
    343. 整数拆分
    413. 等差数列划分
    303. 区域和检索
    62. 不同路径
    char类型与int类型相加
    mybatis里面resultmap的问题
    easyui的datagrid如何获取一个对象里面的成员对象里面的属性?
    ==和equls的区别
    泛型的使用思想
  • 原文地址:https://www.cnblogs.com/lailailai/p/3671687.html
Copyright © 2011-2022 走看看