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
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
这道题创建一个新的node指向head,留作返回用。再创建一个currNode进行node操作用。首先确保currNode和currNode.next不为null,再判断currNode.next的val是不是等于target,是的话让currNode.next等于currNode.next.next,删除之前的currNode.next,不想等的话让currNode等于currNode.next,进行下面的判断。代码如下:
/**
* 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 head;
}
ListNode preHead = new ListNode(0);
preHead.next = head;
ListNode currNode = preHead;
while (currNode != null && currNode.next != null) {
if (currNode.next.val == val) {
currNode.next = currNode.next.next;
} else {
currNode = currNode.next;
}
}
return preHead.next;
}
}