欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Remove Linked List Elements

程序员文章站 2022-04-18 19:23:36
...

Remove all elements from a linked list of integers that have value val.

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if (head == null) {
        	return null;
        }
        ListNode listNode = new ListNode(0);
        listNode.next = head;
        head = listNode;
        while (head.next != null) {
        	if (head.next.val == val) {
        		head.next = head.next.next;
        	} else {
        		head = head.next;
        	}
        }
        return listNode.next;
    }
}