1. 程式人生 > 實用技巧 >Leetcode 19. Remove Nth Node From End of List

Leetcode 19. Remove Nth Node From End of List

Description: Given the head of a linked list, remove the nth node from the end of the list and return its head. Follow up:Could you do this in one pass?

Link: https://leetcode.com/problems/remove-nth-node-from-end-of-list/

解題思路: 刪除倒數第n個元素,且只遍歷一遍。我們熟悉的情況是刪除第m個元素,但如果我們知道連結串列的總長度length,問題就是刪除正向第m = length-n+1個元素。為了只遍歷一次,在計算length的同時,記錄每個node,就可以在一次遍歷結束後找到第m-1個元素,然後刪除它後面的一個元素,將剩餘重新連線。同時考慮刪除head的特殊情況。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        
""" if not head: return head p = head length = 0 nodes = [] while p: nodes.append(p) p = p.next length += 1 if n == length: return head.next else: pre_node = nodes[length - n - 1] pre_node.next
= pre_node.next.next return head

日期: 2020-11-14 Hope the prepare will go well, hope I could make progress and have large improvement.