leetcode--Remove Linked List Elements

本文介绍了一种从整数链表中移除特定值的所有元素的算法,并提供了四种不同的实现方式,包括直接处理头节点、最后处理头节点、创建辅助节点及递归方法。

题目: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

分析:1链表的删除需要知道父节点。

           2中间节点的删除比较简单,头节点的删除需要额外考虑。

One:先处理头结点

public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if(head==null)return null;
       while(head.val==val&&head.next!=null){
           head = head.next;
       }
       if(head.val==val&&head.next==null)return null;
       ListNode res = head;
       while(head.next!=null){
           if(head.next.val==val){head.next=head.next.next;}
           else{head = head.next;}
       }
       return res;
    }
}
Two :先不管头结点,最后处理头结点

public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if(head==null)return null;
       ListNode res = head;
       
       while(head.next!=null){
           if(head.next.val==val){head.next=head.next.next;}
           else{head = head.next;}
       }
       if(res.val==val)
       res = res.next;
       return res;
    }
}
Three:头结点特殊处理,作为新建链表的第二个节点

public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if(head==null)return null;
       ListNode help = new ListNode(0);
       help.next = head;
       ListNode cur = help; 
       
       while(cur.next!=null){
           if(cur.next.val==val){cur.next=cur.next.next;}
           else{cur = cur.next;}
       }
       return help.next;
    }
}

Four:递归的方法 简洁

public ListNode removeElements(ListNode head, int val) {
        if (head == null) return null;
        head.next = removeElements(head.next, val);
        return head.val == val ? head.next : head;
}




评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值