题目链接点击打开链接
这个代码的效率比较低。因为会每个元素都修改一次next指针。解决的办法可以是使用for循环or不用递归来做。但是那样的编程复杂度会提升
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head==null)
{
return null;
}
if(head.val==val)
{
head=head.next;
return removeElements(head, val);
}
else if(head.next==null&&head.val==val)
{
return null;
}
else
{
head.next=removeElements(head.next, val);
return head;
}
}
}
出错过程
Last executed input: [], 1