题目链接:https://leetcode.com/problems/remove-linked-list-elements/
删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6 输出: 1->2->3->4->5
比较简单。
AC 1ms:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head==null)
return null;
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode prev=dummy;
ListNode cur=head;
while(cur!=null){
if(cur.val==val){
cur=cur.next;
prev.next=cur;
}else{
cur=cur.next;
prev=prev.next;
}
}
return dummy.next;
}
}