203. Remove Linked List Elements
Remove all elements from a linked list of integers that have value val.
去掉链表中的val。
代码
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head == null)return head;
while(head.val == val){
head = head.next;
if(head == null)return head;
}
ListNode p = head;
while(p != null && p.next != null){
if(p.next.val == val){
p.next = p.next.next;
}
else
p = p.next;
}
return head;
}
}
思路
遍历链表,将链表中的val去掉。
太久没用java写了,刚开始时,写 !p 不给通过…(吐血)。后面在纸上写注意事项:开头和结尾存在val的情况。因为没想得那么仔细,只想到了开头可能存在连续的val(我都想到这了,竟然没去考虑中间和尾也可能有这种情况!!)。经过几次提交错误后并修改之后,终于通过了,效率和内存还蛮满意的。
感觉以后应该在纸上写上注意事项,并考虑有那些纰漏。