题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
# 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 data = [] res = [] temp = head #将链表中的数据提取出来放入列表list中 while temp is not None: data.append(temp.val) temp = temp.next #特殊情况 if len(data) == n: return head.next #对列表采用切片的方式合并,删除了n节点 data.reverse() res = data[:n-1] + data[n:] res.reverse() print(res) #创建新的链表并返回 headres = ListNode(res[0]) temp = headres for i in range(1,len(res)): newnode = ListNode(res[i]) temp.next = newnode temp = newnode return headres