方法一:数组
# 给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
#
# 示例:
#
# 给定一个链表: 1->2->3->4->5, 和 n = 2.
#
# 当删除了倒数第二个节点后,链表变为 1->2->3->5.
#
#
# 说明:
#
# 给定的 n 保证是有效的。
#
# 进阶:
#
# 你能尝试使用一趟扫描实现吗?
# Related Topics 链表 双指针
# 👍 1169 👎 0
# leetcode submit region begin(Prohibit modification and deletion)
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
curr = head
cache = []
while curr:
cache.append(curr)
curr = curr.next
currIndex = n * (-1)
if n == len(cache):
head = head.next
else:
cache[currIndex - 1].next = cache[currIndex].next
return head
# leetcode submit region end(Prohibit modification and deletion)
方法二:快慢指针
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
dummy = ListNode(0, head)
p1 = head
p2 = dummy
for i in range(n):
p1 = p1.next
while p1:
p1 = p1.next
p2 = p2.next
p2.next = p2.next.next
return dummy.next