【leetcode❤python】 19. Remove Nth Node From End of List

#-*- coding: UTF-8 -*-
#双指针思想,两个指针相隔n-1,每次两个指针向后一步,当后面一个指针没有后继了,前面一个指针的后继就是要删除的节点
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        dummy=ListNode(0)
        dummy.next=head
        p=dummy
        q=dummy
        for i in range(n):
            q=q.next
        while q.next:
            p=p.next
            q=q.next
        
        rec=p.next
        p.next=rec.next
        del rec
        return dummy.next

上一篇:[JavaScript] js 复制到剪切板


下一篇:【leetcode❤python】 234. Palindrome Linked List