zoukankan      html  css  js  c++  java
  • 56-Remove Linked List Elements

    1. Remove Linked List Elements My Submissions QuestionEditorial Solution
      Total Accepted: 61924 Total Submissions: 215788 Difficulty: Easy
      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
    思路:先找到第一个不等于指定值的首节点,作为返回值
    另外在过程中过滤掉等于val值的节点并使前面一个不为val值得节点指向下一个不为val值的节点
    时间复杂度:O(n)
    空间复杂度:O(1)

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* removeElements(ListNode* head, int val) {
            if(head==NULL)return NULL;
            while(head!=NULL&&head->val==val)head=head->next;//找到第一个头部
            ListNode *p=head,*prep=head;
            while(p!=NULL){
                prep=p;
                p=p->next;
                while(p!=NULL&&p->val==val)p=p->next;//直到找到下一个不为val的节点并指向它
                prep->next = p;
            }
            return head;
        }
    };
  • 相关阅读:
    (设计模式)组合模式
    redis 集群部署 (linux)
    redis 集群 配置文件
    redis 外部访问配置(bind正确配置)
    (设计模式)桥模式
    (springboot)freemarker(二)
    (springboot)入门(一)
    (设计模式)抽象工厂
    (设计模式)建造者模式
    (设计模式)原型
  • 原文地址:https://www.cnblogs.com/freeopen/p/5482907.html
Copyright © 2011-2022 走看看