zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    Storm分布式实时流计算框架相关技术总结
    上手开源项目的几点建议【转】
    笔试面试的路上——努力ing
    Storm配置项详解【转】
    storm UI
    leetcode-单词探索
    leetcode-全排列详解(回溯算法)
    leetcode-生成括号(回溯算法)
    leetcode-递增的三元子序列
    leetcode-最长无重复字符的子串
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4860045.html
Copyright © 2011-2022 走看看