题目链接:https://leetcode-cn.com/problems/remove-linked-list-elements/
题目如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode cur=head;
ListNode pre=new ListNode(0);
pre.next=head;//增加一个头节点,并更新新的head,but对pre操作
head=pre;
while(pre.next!=null){
if(cur.val==val) pre.next=cur.next;
else pre=pre.next;
cur=cur.next;
}
return head.next;
}
}