python3删除链表倒数的第n个节点

删除链表的倒数第n个节点

https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6?tpId=188&tags=&title=&diffculty=0&judgeStatus=0&rp=1

分如下两种情况:
1 n=0(链表为空)或n=1(链表只有一个元素),直接返回None
2 常规情况,两个游标,一个游标first_cur先走n步,然后两个游标first_cur/last_cur一起移动。需要注意当n=链表的长度时,即需要删除头节点时的情况。

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

#
# 
# @param head ListNode类 
# @param n int整型 
# @return ListNode类
#
class Solution:
    def removeNthFromEnd(self , head , n ):
        #0 or 1
        cur = head.next if head else head
        if not cur:
            return None

        first_cur=head
        last_cur=head
        while first_cur.next:
            first_cur = first_cur.next 

            if n<=0: last_cur = last_cur.next 
            else: n-=1


        if n>0:head = head.next#n=链表长度,即要删除头节点的情况
        else:last_cur.next = last_cur.next.next 

        return head





全部评论

相关推荐

OPSL:钱确实给的多,但是追责这一点比较迷惑…3个月具体如何计算呢?出勤天数30*3吗?还是21*3呢?万一中间学校有安排怎么办呢?这个得多问一问呀
点赞 评论 收藏
转发
2 收藏 评论
分享
牛客网
牛客企业服务