19. Remove Nth Node From End of List - jiejackyzhang/leetcode-note GitHub Wiki
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
Linked List类题目。
这里的要求是one pass,因此我们用两个指针first和second,两者相差n+1个节点,这样当first到达尾节点的next(null)时,second则是指着倒数n+1个节点,这样只需将second的next指向second.next.next节点,即可将倒数第n个节点删除。
注意点是要删除的可能是头节点,因此我们可以首先创建一个dummy节点,指向头节点,first和second初始都指向dummy。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode first = dummy;
ListNode second = dummy;
// Advances first pointer so that the gap between first and second is n nodes apart
for (int i = 1; i <= n + 1 && first != null; 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 dummy.next;
}
}