1.题目
https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
2.题解
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
思路:
一开始想的,遍历一遍得到长度,然后再遍历一遍,进行运算,觉得有些笨
然后显着直接用传进来的N做为间隔距离,这样子就只用遍历一遍
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode temp = new ListNode(0);
temp.next = head;
ListNode first = temp;
ListNode second = temp;
// Advances first pointer so that the gap between first and second is n nodes apart
for (int i = 1; i <= n + 1; i++) {
first = first.next;
}
// Move first to the end, maintaining the gap
while (first != null) {
first = first.next;
second = second.next;
}
second.next = second.next.next;
return temp.next;
}
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}