題目描述
解題思路
解法一
使用pop函數
將值保存到列表中,使用pop函數刪掉倒數第n個節點,再根據列表重新創建鏈表。
python代碼
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
res = []
while head:
res.append(head.val)
head = head.next
res.pop(-n)
temp = ListNode(-1)
p = temp
for i in res:
p.next = ListNode(i)
p = p.next
return temp.next