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

    Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

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

    Solution:

     1     ListNode *deleteDuplicates(ListNode *head) {
     2         if(head == NULL || head->next == NULL)
     3             return head;
     4         
     5         //remove the head 
     6         ListNode * same_node = NULL;
     7         while(head != NULL) {
     8             if(same_node == NULL) {
     9                 if(head->next != NULL && head->val == head->next->val){
    10                     same_node = head; 
    11                     head = head->next;
    12                 }else {
    13                     break;
    14                 }
    15             }else {
    16                 if(head->val == same_node->val)
    17                     head = head->next;
    18                 else
    19                     same_node = NULL;   
    20             }
    21         }
    22           
    23         if(head == NULL || head->next == NULL)
    24             return head;  
    25             
    26         ListNode * pre = head;
    27         ListNode * same = NULL; 
    28         ListNode * current = pre->next;
    29         while(current != NULL) {
    30             if(same == NULL) {
    31                if(current->next != NULL && current->val == current->next->val){
    32                     same = current;
    33                     pre->next = current->next;
    34                 }else{
    35                     pre = pre->next;
    36                 }
    37                 current = current->next;
    38             }else {
    39                 if(current->val == same->val){
    40                     pre->next = current->next;
    41                     current = current->next;
    42                 }else {
    43                     same = NULL;
    44                 }
    45             }
    46         }
    47         
    48         return head;
    49     }
  • 相关阅读:
    《互联网时代》第三集·能量
    《互联网时代》第二集·浪潮
    java 基础类库之 SysFun
    java 基础类库之 SQLFun
    java 基础类库之 FormatFun
    Java 之 JDBC
    WepE
    MySql学习笔记
    Oracle学习笔记——点滴汇总
    Linux学习笔记——基于鸟哥的Linux私房菜
  • 原文地址:https://www.cnblogs.com/guyufei/p/3417514.html
Copyright © 2011-2022 走看看