【Leetcode 19】刪除鏈表的倒數第n個節點

題目描述

在這裏插入圖片描述

解題思路

解法一

使用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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章