[LeetCode] #203 移除链表元素

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点

输入:head = [1,2,6,3,4,5,6], val = 6

输出:[1,2,3,4,5]

遍历链表,找到相同val,删除

难点在头节点的处理。若头节点等于val,可以从第二个节点开始遍历,返回以第二个节点为头节点的链表

class Solution
{
    public ListNode removeElements(ListNode head, int val)
    {
        while (head != null && head.val == val) head = head.next;
        ListNode p = head;
        if (p != null)
        {
            while (p.next != null)
            {
                if (p.next.val == val)  p.next = p.next.next;
                else p = p.next;
            }
        }
        return head;
    }
}

或者设置虚拟节点,返回虚拟节点的下一个节点

class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode newHead = new ListNode(-1);
        newHead.next = head;
        ListNode p = newHead;
        if(p.val == val)  newHead = new ListNode(p.next.val,p.next.next);
        while(p.next != null){
            if(p.next.val == val) p.next = p.next.next;
            else p = p.next;
        }
        return newHead.next;
    }
}

再或者使用递归

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

知识点:

总结:

posted @ 2021-09-08 20:55  1243741754  阅读(30)  评论(0编辑  收藏  举报