链表天然的递归性

image.png

删除所有值为v的元素

递归函数的“宏观”语意

在以head为头节点的链表中删除值为val的节点,并返回结果链表的头结点

可不可以不返回头节点

不可以,否则递归函数的结果不能和前面的链表连接起来
image.png

  1. public class Simple203 {
  2. static class Solution {
  3. public ListNode removeElements(ListNode head, int val) {
  4. if (head == null) {
  5. return null;
  6. }
  7. head.next = removeElements(head.next, val);
  8. return head.val == val ? head.next : head;
  9. }
  10. }
  11. public static void main(String[] args) {
  12. int[] nums = {1, 2, 6, 3, 6, 5, 7, 5};
  13. ListNode head = new ListNode(nums);
  14. System.out.println(head);
  15. ListNode listNode = new Solution().removeElements(head, 6);
  16. System.out.println(listNode);
  17. }
  18. }

image.png