LCR.P21[删除链表的倒数第N个结点] 方法一:遍历1234567891011121314151617181920212223242526/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode dummy = new ListNode(0, head), p = head; int length = 0; while (p != null) { p = p.next; ++length; } p = dummy; for (int i = 0; i < length - n; ++i) { p = p.next; } p.next = p.next.next; return dummy.next; }} 时间复杂度:$O(n)$ 空间复杂度:$O(1)$ 方法二:快慢指针123456789101112131415161718192021222324/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode dummy = new ListNode(0, head), slow = dummy, fast = head; while (n-- > 0) { fast = fast.next; } while (fast != null) { slow = slow.next; fast = fast.next; } slow.next = slow.next.next; return dummy.next; }} 时间复杂度:$O(n)$ 空间复杂度:$O(1)$