【leetcode刷题】19. Remove Nth Node From End of List

原题链接:https://leetcode.com/problems/remove-nth-node-from-end-of-list/
解题思路:首先遍历一次得到整个list的长度;然后再从头开始计数,如果总长度为total,要删除倒数第n个,则该node与head的距离为n,找到后删除即可
在这里插入图片描述代码:

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        total = 0
        current = head
        if head.next == None:
            return []
        
        while current:
            current = current.next
            total += 1
        
        i = 1    
        current = head
        if total - n == 0:
            head = head.next
        while current:
            if total - n == i:
                follow = current.next
                current.next = follow.next
                # follow.next = None
                break
            else:
                current = current.next
                i += 1
        return head

猜你喜欢

转载自blog.csdn.net/weixin_39746008/article/details/88832330
今日推荐