我的算法之路4-删除链表倒数K个节点

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        firs=head
        while(n>0):
            firs=firs.next
            n-=1
        if not firs:
            return head.next //当第一个指针为空时,删除首节点,返回none

        sec=head
        while(firs.next):
            sec=sec.next
            firs=firs.next
        sec.next=sec.next.next //删除节点,可以利用前节点直接指向后节点,这样就方便操作
        return head
        

猜你喜欢

转载自blog.csdn.net/joaming/article/details/89357787