删除链表中倒数第N和节点
一、问题描述
给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
示例 1:
输入:head = [1,2,3,4,5], n = 2 输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1 输出:[]
示例 3:
输入:head = [1,2], n = 1 输出:[1]
from heapq import heapify, heappop, heappush
from math import inf
from typing import List
from typing import Optional
from clang.cindex import Config
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
head = [1,2,3,4,5]
def creat_tail(li):
head = ListNode(li[0])
tail = head
for element in li[1:]:
node = ListNode(element)
tail.next = node
tail = node
return head
head1 = creat_tail(head)
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
def getlenght(head: ListNode) -> int:
length = 0
while head:
length += 1
head = head.next
return length
cur = dummy = ListNode(0,head)
length = getlenght(head)
for i in range(1, length - n + 1):
cur = cur.next
cur.next = cur.next.next
return dummy.next
def printlink(li):
while li:
print(li.val,end=',')
li = li.next
#printlink(head1)
S= Solution()
printlink(S.removeNthFromEnd(head1,2))
二、结果展示
1,2,3,5,