一、题目描述
给你一个链表,删除链表的倒数第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]
提示:
链表中结点的数目为 sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
`
二、代码
代码如下:
# 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]:
tail=head
list=[]
#将链表保存至list中
while(tail):
list.append(tail.val)
tail=tail.next
list.pop(len(list)-n)
#list为空时
lenth=len(list)
if lenth==0:
return None
#list不为空时,将list列表转换为单链表
head=ListNode(list[0],None)
tail=head
for i in range(lenth-1):
node=ListNode(list[i+1],None)
tail.next=node
tail=node
return head
三、解题思路
PS:个人能力有限,不考虑时间空间最优。
本题需要对于单链表有一点了解,在进行删减过程中,可以将单链表先转化为list列表,然后对list列表进行删除操作,最后再将删减好的list列表转换为单链表。