1、题目描述
给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
示例 1:
输入:head = [1,2,3,4,5], n = 2 输出:[1,2,3,5]
2、初始思路
2.1 思路
先计算整个链表的长度,然后利用p2.next = p2.next.next删除指定的节点。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:m = 0p1 = headwhile p1:m+=1p1 = p1.next#print(m)if m == n:return head.nexti = 0p2 = headwhile i < m-n-1:p2 = p2.nexti += 1p2.next = p2.next.nextreturn head