LeetCode_Everyday:019 Remove Nth Node From End of List

LeetCode_Everyday:019 Remove Nth Node From End of List


LeetCode Everyday:坚持价值投资,做时间的朋友!!!

题目:

给定一个链表,删除链表的倒数第n个节点,并且返回链表的头结点。
进阶:你能尝试使用一趟扫描实现吗?

示例:

  • 示例 1:
    给定一个链表: 1->2->3->4->5, 和 n = 2.
    当删除了倒数第二个节点后,链表变为 1->2->3->5.
    

代码

方法一: 递归 题解

执行用时:32 ms, 在所有 Python3 提交中击败了98.09%的用户
内存消耗:13.5 MB, 在所有 Python3 提交中击败了5.41%的用户

# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
        
class Solution:
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        global i   
        if head is None:
            i=0
            return None
        head.next = self.removeNthFromEnd(head.next,n)
        i+=1
        return head.next if i==n else head

"""
For Example:    input:    1->2->3->4->5, 和 n = 2
               output:    1->2->3->5
"""
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)
n = 2
                
solution = Solution()
result = solution.removeNthFromEnd(head, n)
print('输出为:%d->%d->%d->%d' % (result.val, result.next.val, result.next.next.val, result.next.next.next.val))

方法二: 快慢指针 题解

执行用时:48 ms, 在所有 Python3 提交中击败了35.30%的用户
内存消耗:13.7 MB, 在所有 Python3 提交中击败了5.41%的用户

# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
        
class Solution:
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        dummy = ListNode(0)
        dummy.next = head
        fast,slow = dummy,dummy
        for  i in range(n+1):
            fast = fast.next
        while fast is not None: 
            fast = fast.next
            slow = slow.next
        slow.next = slow.next.next
        return dummy.next

"""
For Example:    input:    1->2->3->4->5, 和 n = 2
               output:    1->2->3->5
"""
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)
n = 2
                
solution = Solution()
result = solution.removeNthFromEnd(head, n)
print('输出为:%d->%d->%d->%d' % (result.val, result.next.val, result.next.next.val, result.next.next.next.val))

参考

  1. https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/python-di-gui-by-adamch0u/
  2. https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/guan-fang-ti-jie-de-python3-shi-xian-fu-ya-jie-dia/

此外

  • 原创内容转载请注明出处
  • 请到我的GitHub点点 star
  • 关注我的 CSDN博客
  • 关注我的哔哩哔哩
  • 关注公众号:CV伴读社

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章