链表--移除链表元素

42 阅读1分钟

删除链表中等于给定值 val 的所有节点。

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

代码:

public class RemoveElements {
    public static Node removeElements(Node head, int val) {
        if (head == null) {
            return head;
        }
        // 定义一个虚拟头结点
        Node dummyHead = new Node(-1);
        dummyHead.next = head;
        Node cur = dummyHead;
        while (cur.next != null) {
            if (cur.next.val == val) {
                cur.next = cur.next.next;
            } else {
                cur = cur.next;
            }
        }
        return dummyHead.next;
    }

    public static void main(String[] args) {
        Node n3 = new Node(3, null);
        Node n2 = new Node(2, n3);
        Node n1 = new Node(1, n2);
        Node head = new Node(0, n1);
        Node node = removeElements(head, 2);
    }


   static class Node {
        int val;
        Node next;

        public Node() {
        }

        public Node(int val) {
            this.val = val;
        }

       public Node(int val, Node next) {
           this.val = val;
           this.next = next;
       }
   }

}