LeetCode-19 - Remove Nth Node From End of List

Given a linked list, remove the nth node from the end of list and return its head.

For example,

   Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.
Try to do this in one pass.

Solution1

此解法采用最为直观的做法,然后出现边界问题,再采用打patch的方式一一避免。

!! 不应该!!

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

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        if not head.next and n == 1:
            return None
        amap = {}
        index = 1
        node = head
        while node:
            #print node
            amap.update({index: node})
            node = node.next
            index += 1
        if not len(amap) - n:
            head = head.next
        else:
            node = amap.get(len(amap) - n)
            node.next = node.next.next 
        return head

Solution2

简介明了

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

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        prevNode = None
        slowNode = head
        fastNode = head
        while n > 0:
            fastNode = fastNode.next
            n -= 1
        
        while fastNode:
            fastNode = fastNode.next
            prevNode = slowNode
            slowNode = slowNode.next
        
        if prevNode == None:
            head = head.next
            return head
        
        prevNode.next = slowNode.next
        return head

反思

对于算法题目,缺少最基本的素养,采用最暴力的方式来求解。

推荐阅读更多精彩内容