一、题目内容

image.png

二、题解

解法1:

思路

快慢指针

代码

  1. public class Solution {
  2. public ListNode removeNthFromEnd(ListNode head, int n) {
  3. ListNode fast = head, slow = head;
  4. for (int i = 0; i < n; i++) {
  5. fast = fast.next;
  6. }
  7. if(fast == null){
  8. return head.next;
  9. }
  10. while (fast.next != null) {
  11. fast = fast.next;
  12. slow = slow.next;
  13. }
  14. slow.next = slow.next.next;
  15. return head;
  16. }
  17. }