思路:同剑指14.链表中倒数第k个结点
class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { /** * 方法1:计算链表长度,相当于两次遍历链表 */ /* ListNode dummyHead = new ListNode(-1); dummyHead.next = head; int len = 0; ListNode cur = dummyHead; while (cur != null) { len ++; cur = cur.next; } cur = dummyHead; for (int i = 0; i < len - n - 1; i++) { cur = cur.next; } cur.next = cur.next.next; return dummyHead.next; */ /** * 方法2: 快慢指针。 一次遍历 */ ListNode dummyHead = new ListNode(-1); dummyHead.next = head; ListNode fast = dummyHead, slow = dummyHead; for (int i = 0; i < n + 1; i++) { fast = fast.next; } while (fast != null) { fast = fast.next; slow = slow.next; } slow.next = slow.next.next; return dummyHead.next; } }