lc19. 删除链表的倒数第 N 个结点

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        first = head
        list_length = 1
        while first.next != None:
           list_length += 1
           first = first.next
        # 特殊处理n=list_length的情况,此时删除的是头结点
        if n == list_length:
            head_next = head.next
            head.next = None
            return head_next
        second = head
        nth_count = 1
        while nth_count < list_length - n + 1:
            if nth_count == list_length - n:
                node_after_nth = second.next.next
                second.next.next = None
                second.next = node_after_nth
                break
            nth_count += 1
            second = second.next
        return head

 

posted @ 2022-05-05 17:12  stronger_el  阅读(26)  评论(0)    收藏  举报