19. 删除链表的倒数第 N 个结点
已解答
中等
相关标签
相关企业
提示
给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点
# 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: Optional[ListNode]
:type n: int
:rtype: Optional[ListNode]
"""
# 用list很好实现
# 可以双指针,慢的慢n个,当都到达的时候,就是对了
low = head
fast =head
prev = None
next_node = fast.next
for i in range(n):
fast = fast.next
while fast!=None:
prev = low
low=low.next
next_node = low.next
fast = fast.next
if prev!=None:
prev.next=next_node
return head
else:
return head.next
很简单,可以用list直接做,高级做法是双指针