# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param {ListNode} head
# @param {integer} n
# @return {ListNode}
def removeNthFromEnd(self, head, n):
q = p = head
dis = 0
if head == None or (head.next==None and n==1):
return None
while dis != n+1 or q!= None:
if dis>n:
p=p.next
dis-=1
if q != None:
q = q.next
dis+=1
if q == None and dis < n+1:
return head.next
if p.next != None:
p.next = p.next.next
return head
LeetCode #19 Remove Nth Node From End of List
本文介绍了一种高效算法,用于在单链表中移除倒数第N个节点。通过两个指针的巧妙运用,该算法能够在遍历一次链表后找到目标节点并完成删除操作。


被折叠的 条评论
为什么被折叠?



