0
点赞
收藏
分享

微信扫一扫

虚拟节点删除确定值的节点

J简文 2022-02-11 阅读 78

收获:

遍历整个链表判断条件是:cur.next!=null;

链表遍历,中间指针的cur当前节点,当前节点变化的条件是,当前节点的next值不为val;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode header = new ListNode(-1);
        header.next=head;
        ListNode cur = header;//当前节点
        while(cur.next !=null){//遍历到最后一个节点
            if(cur.next.val==val){
                cur.next = cur.next.next;
            }else{
                cur = cur.next;//当前节点指针的变化
            }
        }
         return header.next;
        
        
       
    }
}
举报

相关推荐

0 条评论