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.
Subscribe to see which companies asked this question
/**
* 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 pre=new ListNode(-1);
pre.next=head;
ListNode cur=pre.next;
// 结果返回节点
ListNode res=pre;
while(cur!=null){
if(cur.val==val){
pre.next=cur.next;
cur.next=null;
cur=pre.next;
}
else{
pre=pre.next;
cur=cur.next;
}
}
return res.next;
}
}