Leetcode 19. Remove Nth Node From End of List
题目描述:删除从尾节点数其的第
n
个节点,并返回删除后的头结点。
题目链接:Leetcode 19. Remove Nth Node From End of List
链表的问题只要用快慢指针+翻转操作+成环重头跑,基本能解决,注意利用dummy
等辅助指针指向下一个头呀之类的。
这个题目让快指针先跑n次,然后快慢一起跑,当快指针到达结尾的时候,慢指针达到要删除节点的前一个节点。
代码如下
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
fast = slow = head
for _ in range(n): #先走n步 这样快指针到达到结尾的时候慢指针指向该删除的点。
fast = fast.next #这种题 什么第K个结点 什么从后面数起第k个结点,都用快慢指针,要么让快指针先走k
#走的同时还可以翻转链表 然后怎么怎么de .
if not fast:
return head.next
while fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return head