题目: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
思路:新建一个val=-1的头节点,从head结点开始,判断值是否与目标值相等,不相等就加在新建结点后
代码:
public class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode cur = new ListNode(-1);
ListNode res = cur ;
while(head!=null){
if(head.val!=val){
cur.next = head;
cur = cur.next;
}
head = head.next;
}
cur.next = null;
return res.next ;
}
}