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
思路:判断p.next.val等不等于val等于的话就p.next=p.next.next;
代码如下(已通过leetcode)
public class Solution {
public ListNode removeElements(ListNode head, int val) {
while(head!=null && head.val==val) head=head.next;
ListNode p=head;
if(p==null) return null;
while(p!=null&&p.next!=null) {
if(p.next.val==val) {
if(p.next.next==null) p.next=null;
else p.next=p.next.next;
}
else p=p.next;
}
return head;
}
}