[leetcode]双指针 Remove Nth Node From End of List

Remove Nth Node From End of List

这题我觉得应该算easy题里面,涉及到的知识确实不多:

  • 看到链表能不能反应过来使用指针
  • 对于这个n-th节点的边界情况

自己一开始就能想到前后指针,两个指针的间隔为n,然后同步移动,当后指针到末尾的时候,前指针的位置就是需要进行链表删除的上一个位置,很方便。
但是又一个坑就在于如果要删除头节点怎么办,因为上面的解法固定了我们的前指针位于的是链表删除的上一个位置。因此就需要再头指针的前命构建一个虚节点,一开始前指针指向的是虚节点,就解决这个问题了。
自己的代码:

# # 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
        """
        v_head=ListNode(0)
        v_head.next=head
        f=v_head
        l=v_head
        for i in range(n):
            l=l.next            
        while l.next!=None:
            f=f.next
            l=l.next
        f.next=f.next.next
        return v_head.next

leetcode上最快的代码:
思路还是一样的,没有太大的区别,不过语义化的变量命名值得学习!

# 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
        """
        dummy = ListNode(-1)
        dummy.next = head
        curr = dummy
        while curr.next and n > 0:
            curr = curr.next
            n -= 1
            
        if n > 0:
            return dummy.next
        
        slow, fast = dummy, curr
        while fast.next:
            slow = slow.next
            fast = fast.next
            
        slow.next = slow.next.next
        return dummy.next

猜你喜欢

转载自blog.csdn.net/qq_34661230/article/details/85543170