删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
注意:一定要判断头结点是否为被删除的结点,如果要删除,则要修改头结点
class Solution {
public ListNode removeElements(ListNode head, int val) {
//如果头结点为空,则直接返回
if(head == null) {
return head;
}
ListNode p = head, q = head.next;
while(q != null) {
//删除结点
if(q.val == val) {
p.next = q.next;
q = q.next;
}else{
p = p.next;
q = q.next;
}
}
//判断头结点是否为要删除的结点
if(head.val == val) {
head = head.next;
}
return head;
}
}