Remove Linked List Elements 删除单链表里边指定的元素

来源:互联网 发布:sql语句查询例子 编辑:程序博客网 时间:2024/06/07 10:28

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


public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        //while(head.val==val){如果写成这样,则报错为空指针异常
        while(head!=null && head.val==val){
            head=head.next;//如果Head为待删除节点的话,一直删除
        }
        if(head==null) return head;//判断链表是否为空
        ListNode pre;
        pre=head;
        while(pre.next!=null){//因为pre=head已经不满足待删除了,所以直接判断pre.next.val
            if(pre.next.val!=val)    pre=pre.next;
            else    pre.next=pre.next.next;
        }
        return head;
    }
}



转发的这个递归http://bookshadow.com/weblog/2015/04/24/leetcode-remove-linked-list-elements/

public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if (head == null) return null;
        head.next = removeElements(head.next, val); //head.next=便包含了是否被删除的承接关系
        return head.val == val ? head.next : head;
    }
}



0 0
原创粉丝点击