问题
删除链表中等于给定值 val 的所有节点。
例子
思路
两个指针,pre, now
-
方法1
-
方法2
代码
//方法1
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode hhead = new ListNode(-1);
hhead.next=head;
ListNode pre=hhead;
while(head!=null) {
if(head.val==val) {
ListNode temp = head.next;
pre.next=temp;
head=temp;
}else{
pre=head;
head=head.next;
}
}
return hhead.next;
}
}
//方法2