• Remove Linked List Elements


    Remove all elements from a linked list of integers that have value val.

    Example
    Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6,  val = 6
    Return: 1 --> 2 --> 3 --> 4 --> 5

    Credits:
    Special thanks to @mithmatt for adding this problem and creating all test cases.

    Wrong Edition.

     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* removeElements(ListNode* head, int val) {
    12         if(!head) return head;
    13         if(!head->next) return head->val == val ? NULL : head;
    14         
    15         while(head->val == val)
    16             head = head->next; //avoid the case where continuous val at the head
    17         if(!head) return NULL;
    18         
    19         ListNode* current = head;
    20         while(current){
    21             if(current->next->val == val){
    22                 ListNode* temp = current->next;
    23                 while(temp && temp->val == val)
    24                     temp = temp->next;
    25                 current->next = temp;
    26             }
    27             current = current->next;
    28         }
    29         return head;
    30     }
    31 };
    View Code

    Runtime: 36ms

     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* removeElements(ListNode* head, int val) {
    12         if(!head) return head;
    13         
    14         ListNode* pre = new ListNode(0);
    15         pre->next = head;
    16         ListNode* move = pre;
    17         
    18         while(move->next){
    19             if(move->next->val == val)
    20                 move->next = move->next->next;
    21             else
    22                 move = move->next;
    23         }
    24         return pre->next;
    25     }
    26 };
  • 相关阅读:
    JAVA规则引擎 -- Drools
    Spring多数据源的配置和使用
    nginx反向代理与正向代理的区别
    优化你的java代码性能
    java 代码优化
    java常用的设计模式
    Java中的异常处理从概念到实例
    详解JVM工作原理和特点
    mysql性能优化-慢查询分析、优化索引和配置
    外网不能访问部署在虚机的NodeJs网站(80端口)
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4860045.html
Copyright © 2020-2023  润新知