链表元素删除

题目:

删除单链表中的元素

解答:

package com.interview.meicai;
 
public class ListNode {
    int val;
    ListNode next;
 
    public  ListNode(int val){
        this.val = val;
    }
 
    public static void main(String[] args) {
        ListNode listNode = new ListNode(1);
 
        listNode.next = new ListNode(2);
 
    }
}
 
// 删除链表指定元素
class Solution{
 
    public ListNode removeElements(ListNode head, int val){
        ListNode prevNode = head;
        ListNode current = head;
        while (current.val != val){
            if(current.next == null){
                return head;
            }else{
                prevNode = current;
                current = current.next;
            }
        }
        if(current == head){
            head = current.next;
        }else{
            prevNode.next = current.next;
        }
 
        return head;
    }
 
}