leetcode_python_删除链表的倒数第N个节点

第一轮:

方法1:求长度,减去n得到被删除节点的前一个节点,直接跨越链接。若num=0则删除的是首节点

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next 
def LengthNode(self):
    length = 0
    while self:
        length += 1
        self = self.next
    return length 
class Solution:
  
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        first = head
        length = LengthNode(head)
        num = length - n
        if num == 0:
            return first.next
        count = 1
        while count < num: 
            head = head.next
            # print(head.next.val)
            count += 1
        #找到被删节点的前一个节点 
        if head.next.next:
            head.next = head.next.next
        else:
            head.next = None
        return first

 

posted @ 2021-06-01 17:24  泊鸽  阅读(67)  评论(0)    收藏  举报