# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defremoveNthFromEnd(self, head: ListNode, n: int) -> ListNode: defreverseList(head): if head isNoneor head.nextisNone: return head; pre = None; cur = head; h = head; while cur: h = cur; tmp = cur.next; cur.next = pre; pre = cur; cur = tmp; return h length = 0 tmp = head while tmp: length += 1 tmp = tmp.next if n == 1: return reverseList(reverseList(head).next) if length == n: return head.next head = reverseList(head) count = 1 tmp = head while count != n - 1: count += 1 tmp = tmp.next tmp.next = tmp.next.next