19 Remove Nth Node from End of the List
使用快慢指针的方法,维护两个指针,指针的间距是N, 当快指针为空的时候,慢指针指向了需要删除的节点。
两个技巧,使用dummy头在全部的元素之前,另一个技巧将前面的过程合并成一个循环来写。
Python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
dummy = ListNode(0)
dummy.next = head
fast, slow = dummy, dummy
while fast.next:
if n <= 0:
slow = slow.next
fast = fast.next
n -= 1
if slow.next is not None:
slow.next = slow.next.next
return dummy.next
Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummyHead = new ListNode(0);
dummyHead.next = head;
ListNode slow = dummyHead;
ListNode fast = dummyHead;
while(fast.next != null){
if (n <= 0){
slow = slow.next;
}
fast = fast.next;
n --;
}
if(slow.next != null){
slow.next = slow.next.next;
}
return dummyHead.next;
}
}