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.

    首先我们把key设为非头节点的值,然后遍历链表,当节点值等于key时删除,不能于时更新key.

     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         // Start typing your C/C++ solution below
    13         // DO NOT write int main() function
    14         if (head == NULL)
    15             return NULL;
    16         
    17         ListNode *pPre = NULL;
    18         ListNode *p = head;
    19         int key = INT_MAX;
    20         
    21         while(p)
    22         {
    23             if (key != p->val)
    24             {
    25                 key = p->val;
    26                 pPre = p;
    27                 p = p->next;
    28             }
    29             else
    30             {
    31                 ListNode *pNext = p->next;
    32                 if (pPre)
    33                     pPre->next = pNext;
    34                 delete p;
    35                 p = pNext;
    36             }
    37         }
    38         
    39         return head;
    40     }
    41 };
  • 相关阅读:
    HNOI 2006 BZOJ 1195 最短母串
    BZOJ 3029 守卫者的挑战
    Codeforces 401D Roman and Numbers
    ZJOI2010 数字计数
    BZOJ 3329 Xorequ
    Codeforces 235 C
    SPOJ 8222 Substrings
    BZOJ 1396 识别子串
    (模板)归并排序
    poj3122 Pie (二分)
  • 原文地址:https://www.cnblogs.com/chkkch/p/2777291.html
Copyright © 2011-2022 走看看