[leetcode]203. Remove Linked List Elements链表中删除节点

这道题很基础也很重要

重点就是设置超前节点

public ListNode removeElements(ListNode head, int val) {
        //超前节点
        ListNode pre = new ListNode(0);
        pre.next = head;
        ListNode res = pre;
        while (pre!=null&&pre.next!=null)
        {
            if (pre.next.val==val)
            {
                pre.next = pre.next.next;
                //注意这里要跳出循环,因为节点已经跳跃一位了,不需要再更新超前节点
                continue;
            }
            pre = pre.next;
        }
        //这里不能返回head,因为head可能已经被孤立出来了
        return res.next;
    }

 

posted @ 2018-02-13 11:21  stAr_1  阅读(92)  评论(0编辑  收藏  举报