题目描述:
解法思路:
这道题我们可以采用递归的方法去解答。首先不断递归遍历链表中的元素,当发现目标元素,返回目标元素的next即可,从而达到删除链表元素的目的。当遍历到null值时,说明已经遍历到链表底部,直接返回删除元素后的链表即可。
代码实现:
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if (head == null)
return head;
if (head.val == val)
return head.next;
head.next = deleteNode(head.next, val);
return head;
}
}
执行结果: