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.