题目:203. 移除链表元素
题目:203. 移除链表元素
概述
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
方式一(添加一个虚拟头结点)
public ListNode removeElements(ListNode head, int val) {
        if (head == null) {
            return head;
        }
        ListNode res = new ListNode(-1, head);
        ListNode temp = res;
        while (temp != null && temp.next != null) {
            if (temp.next.val == val) {
                temp.next = temp.next.next;
                continue;
            }
            temp = temp.next;
        }
        return res.next;
    }
方式二(更新头结点位置,使第一个节点不等于要删除的节点)
 public ListNode removeElements(ListNode head, int val) {
        //改变头结点位置
        while (head != null && head.val == val) {
            head = head.next;
        }
        //有可能全是相同元素,改变万头结点位置后,链表为空,直接返回即可
        if (head == null) {
            return head;
        }
        ListNode res = head;
        while (head != null && head.next != null) {
            if (head.next.val == val) {
                head.next = head.next.next;
                continue;
            }
            head = head.next;
        }
        return res;
    }
方式三(递归)
 public ListNode removeElements(ListNode head, int val) {
        if (head == null) {
            return head;
        }
        if (head.val == val) {
            head = removeElements(head.next, val);
        } else {
            head.next = removeElements(head.next, val);
        }
        return head;
    }
    努力奔跑,是为了追上曾经被寄予厚望的自己。
 
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号