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/

此外

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值