给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
**进阶:**你能尝试使用一趟扫描实现吗?
示例 1:
输入:head = [1,2,3,4,5], n = 2 输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1 输出:[]
示例 3:
输入:head = [1,2], n = 1 输出:[1]
n
个结点,可以联想到 倒数第n个节点和链表结束的null节点是一个 “窗口”,知道这一点我们维护这个窗口就好了public ListNode removeNthFromEnd(ListNode head, int n) { // [d,1,2,3,4,5,null] if (head == null || n <= 0) return head; ListNode d = new ListNode(-1); d.next = head; ListNode slow = d; ListNode fast = d; while (n-- >= 0) { // n + 1 fast = fast.next; } while (fast != null) { slow = slow.next; fast = fast.next; } slow.next = slow.next.next; return d.next; }
该方法遍历了链表2次,极端情况如果链表过长,n过大,代价挺大,不推荐
public ListNode removeNthFromEnd(ListNode head, int n) { // [d,1,2,3,4,5,null] if (head == null || n <= 0) return head; ListNode d = new ListNode(-1); d.next = head; ListNode p = d; int len = 0; while (p != null) { len++; p = p.next; } p = d; int dis = len - n - 1; for (int i = 0; i < dis; i++) { p = p.next; } p.next = p.next.next; return d.next; }