zoukankan      html  css  js  c++  java
  • leetcode203. 移除链表元素

    方法一(删除头结点时另做考虑)

    class Solution {
    public:
        ListNode* removeElements(ListNode* head, int val) {
            
            if(head!=NULL && head->val==val)
            {
                head=head->next;
            }
            if(head==NULL) return NULL;
            //处理第一位是val的情况
            while(head->val==val)
            {
                head=head->next;
                if(head==NULL) return NULL;
            }
            ListNode *curr=head->next;
            ListNode *pre=head;
            while(curr!=NULL)
            {
               
                if(curr->val==val)
                {
                    pre->next=curr->next;
                }
                else
                    pre=curr;
                curr=curr->next;
            }
            return head;
            
        }
    };

    方法二(添加一个虚拟头结点)

    class Solution {
    public:
        ListNode* removeElements(ListNode* head, int val) {
            
            
            ListNode* vir=new ListNode(-1);
            vir->next=head;
            ListNode *pre=vir;
            while(pre->next!=NULL)
            {
               
                if(pre->next->val==val)
                {
                    pre->next=pre->next->next;
                }
                else
                    pre=pre->next;
            }
            return vir->next;
            
        }
    };

    方法三(递归)

    class Solution {
        public ListNode removeElements(ListNode head, int val) {
           if(head==null)
               return null;
            head.next=removeElements(head.next,val);
            if(head.val==val){
                return head.next;
            }else{
                return head;
            }
        }
    }
  • 相关阅读:
    倒水问题(BFS)
    小程序整理
    微信小程序--录音
    mpvue
    hbuilder 打包 vueAPP
    react rem
    react 关闭eslint 配置
    react axios 配置
    react 路由之react-router-dom
    react mobx 装饰器语法配置
  • 原文地址:https://www.cnblogs.com/renzmin/p/11877784.html
Copyright © 2011-2022 走看看