题解 | #删除链表的倒数第n个节点#

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

http://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6

哈希表储存nodes并读取

Extreme cases:

1.head = {} (n=0);

2.n=1;

3.删除的节点是第一个节点;

4.head只有一个节点

class Solution:
    def removeNthFromEnd(self , head: ListNode, n: int) -> ListNode:
        # write code here
        #Extreme cases 1
        if not head:
            return head
        hashtable = {}
        pre = head
        i = 0
        while head:
            hashtable[i] = head
            head = head.next
            i += 1
        if i-n-1 in hashtable:
            #Extreme cases 2
            hashtable[i-n-1].next = hashtable[i-n].next
        else:
            #Extreme cases 3
            pre = hashtable[i-n].next
        return pre

time complexity = O(n)

space complexity = O(1)

全部评论

相关推荐

点赞 1 评论
分享
牛客网
牛客企业服务