• 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     }
  • 相关阅读:
    jquery 读取 xml 属性等于某值的 方法
    jquery 定时器
    jquery div 滚动条 最底部
    ajax success 不能返回值解决方案 async:false
    wiki 使用说明
    thinkphp 二维码封装函数
    100本书 慢慢来读
    2013 来了
    jquery 解析 xml
    键盘按键 事件
  • 原文地址:https://www.cnblogs.com/guyufei/p/3417514.html
Copyright © 2020-2023  润新知