美文网首页
203. 移除链表元素

203. 移除链表元素

作者: bangbang2 | 来源:发表于2020-08-20 21:23 被阅读0次
    image.png

    为什么要引入dummy头节点?
    如果删除head头节点,那么就无法返回head,之前我的返回是head

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode removeElements(ListNode head, int val) {
            if(head==null) return null;
            if(head.next==null&&head.val==val) return null; 
            ListNode dummy=new ListNode(0);
            dummy.next=head;
            ListNode start=head;
            ListNode end=dummy;
            while(start!=null){
                if(start.val==val){
                    end.next=start.next;
                }else  end=end.next;//如果不相等,end向前移动
                start=start.next;
            }
           
            return dummy.next;
        }
    }
    

    相关文章

      网友评论

          本文标题:203. 移除链表元素

          本文链接:https://www.haomeiwen.com/subject/vdgejktx.html