image.png

    1. // 快慢指针
    2. public ListNode removeNthFromEnd(ListNode head, int n) {
    3. ListNode fast = head;
    4. ListNode slow = head;
    5. for (int i = 0;i < n; i++) {
    6. fast = fast.next;
    7. }
    8. if (fast == null) {
    9. head = head.next;
    10. return head;
    11. }
    12. while (fast.next != null) {
    13. fast = fast.next;
    14. slow = slow.next;
    15. }
    16. slow.next = slow.next.next;
    17. return head;
    18. }
    19. // 递归版本
    20. class Solution {
    21. public ListNode removeNthFromEnd(ListNode head, int n) {
    22. return remove(head,n) == n ? head.next : head;
    23. }
    24. public int remove (ListNode head, int n) {
    25. if (head.next == null) {
    26. return 1;
    27. }
    28. int count = remove(head.next,n);
    29. if (count == n) {
    30. if (count == 1) {
    31. head.next = null;
    32. } else {
    33. head.next = head.next.next;
    34. }
    35. }
    36. return count + 1;
    37. }
    38. }