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))
参考
- https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/python-di-gui-by-adamch0u/
- 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/