18 leetcode - Remove Nth Node From End of List

    xiaoxiao2021-11-28  30

    指针追赶。 设两个指针,一个先走n步,然后同时走。

    #!/usr/bin/python # -*- coding: utf-8 -*- ''' 英文:Given a linked list, remove the nth node from the end of list and return its head. 中文:移除倒数第n个节点 举例: Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. ''' # 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 """ first = head second = head while n: first = first.next n -= 1 if first == None:#已经到了结尾了 if n > 0: #说明n已经超过了链表的长度,直接返回头节点即可 return head else:#恰好删除头节点 return head.next #删除的节点在链表中间 while first.next: first = first.next second = second.next #second.next为倒数第n个节点,让second.next = second.next.next就跳过了倒数第n个节点 second.next = second.next.next return head
    转载请注明原文地址: https://ju.6miu.com/read-678560.html

    最新回复(0)