题目描述
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
题解
一次遍历法(推荐)
此处是官方的一次遍历法。
使用两个指针。第一个指针从列表的开头向前移动 n+1 步,而第二个指针将从列表的开头出发。现在,这两个指针被 n 个结点分开。我们通过同时移动两个指针向前来保持这个恒定的间隔,直到第一个指针到达最后一个结点。此时第二个指针将指向从最后一个结点数起的第 n 个结点。我们重新链接第二个指针所引用的结点的 next 指针指向该结点的下下个结点。

public ListNode RemoveNthFromEnd(ListNode head, int n){var dummy = new ListNode(0) { next = head };var first = dummy;var second = dummy;// Advances first pointer so that the gap between first and second is n nodes apartfor (var i = 1; i <= n + 1; i++){first = first.next;}// Move first to the end, maintaining the gapwhile (first != null){first = first.next;second = second.next;}second.next = second.next.next;return dummy.next;}
借助 List 和哑节点
遍历将链表问题转换为 List 问题。
public ListNode RemoveNthFromEnd(ListNode head, int n){var dummy = new ListNode(0) { next = head };var list = new List<ListNode> { dummy };var first = dummy;while (first != null){list.Add(first);first = first.next;}var length = list.Count;if (n == 1){list[length - 2].next = null;}else{list[length - (n + 1)].next = list[length - n + 1];}return dummy.next;}
