python---删除链表中倒数第n个节点

"""
Definition of ListNode
class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""


class Solution:
    """
    @param: head: The first node of linked list.
    @param: n: An integer
    @return: The head of linked list.
    """


def removeNthFromEnd(self, head, n):
    tem = head
    num_tem = n
    #如果链表为空就直接返回None
    if not head:
        return None
    # 得到倒数第n个节点,注意倒数第一个是最后一个,
    # 所以控制的num_tem是大于1,这样两个tem节点的位置就是第n个位置,
    # 数组的位置是从0开始的,也就是数组的n-1位
    while tem and num_tem > 1:
        tem = tem.next
        num_tem -= 1
    tem_n = tem
    head_n = head
    pre = head
    #在得到第n个位置后,一直循环到最后一位,那么head_n就是倒数第n个元素,
    # pre是第n-1个元素(n>1)
    while tem_n.next:
        tem_n = tem_n.next
        pre = head_n
        head_n = head_n.next
    #如果倒数第n个元素就是第1个元素,直接返回第二个元素开始即可
    if head_n==head:
        return head.next
    #否则只需要倒数第n-1个元素的下一个元素是倒数第n+1元素即可
    else:
        pre.next = head_n.next
        return head

你可能感兴趣的:(python---删除链表中倒数第n个节点)