Leetcode - 19 countdown list of deleted N nodes python

Disclaimer: This article is original, All Rights Reserved https://blog.csdn.net/weixin_41864878/article/details/91042588

Given a list, delete list reciprocal of n nodes, and returns to the head node list.

Example:

Given a list: 1-> 2-> 3-> 4-> 5, and n = 2.

When the removed penultimate node, the list becomes 1-> 2-> 3-> 5 Description:

N is given to ensure effective.

Advanced:

You can try to use one pass to achieve it?

With two pointers, a first pointer to go first step, after the establishment of the second pointer, and then go with two pointers, a pointer to go until the first end, the second pointer in this case the n-1 is the inverse of position, and the next next.next n-1 are connected together on ok

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        steps = 0
        node = head
        if not node or not node.next: return None #只有1个节点时也返回None
        while steps < n-1 and node:
            node = node.next
            steps+=1
        rem = head
        node = node.next # node再走一步
        if not node: #如果这时已经到了末尾,说明要删除的是头节点
            head = head.next
            return head
        while node.next:
            node = node.next
            rem = rem.next
        if n == 1: rem.next = None #如果n=1,说明要删除的是尾节点
        else: rem.next = rem.next.next
        return head     

Guess you like

Origin blog.csdn.net/weixin_41864878/article/details/91042588