不知道为啥这题是中等难度,似乎相对简单,只需要下列两步就可以完美解决了。

  1. 得到链表的总长度m; 2.链表从头前移m-n,然后把那个节点删了就行。 然后稍微注意改下边界条件就行。
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 25 10:29:14 2022

@author: Administrator
"""
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head ListNode类 
# @param n int整型 
# @return ListNode类
#
class Solution:
    def removeNthFromEnd(self , head: ListNode, n: int) -> ListNode:
        # write code here
        size=0 ; cur=head
        while cur :
            size+=1
            cur=cur.next
        if size==0:
            return None
        elif size == 1:
            if n==0:
                return head
            else:
                return None
        if size == n:
            return head.next
        else:
            m = size-n
            cur=head ; pre = None
            for i in range(m):
                pre=cur
                cur = cur.next
            pre.next = cur.next
        return head

head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head = Solution().removeNthFromEnd(head , 2)
cur=head
while cur:
    print(cur.val)
    cur = cur.next