mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Update 0019.删除链表的倒数第N个节点.md
This commit is contained in:
@ -127,21 +127,29 @@ Python:
|
||||
# def __init__(self, val=0, next=None):
|
||||
# self.val = val
|
||||
# self.next = next
|
||||
|
||||
class Solution:
|
||||
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
|
||||
head_dummy = ListNode()
|
||||
head_dummy.next = head
|
||||
# 创建一个虚拟节点,并将其下一个指针设置为链表的头部
|
||||
dummy_head = ListNode(0, head)
|
||||
|
||||
slow, fast = head_dummy, head_dummy
|
||||
while(n>=0): #fast先往前走n+1步
|
||||
# 创建两个指针,慢指针和快指针,并将它们初始化为虚拟节点
|
||||
slow = fast = dummy_head
|
||||
|
||||
# 快指针比慢指针快 n+1 步
|
||||
for i in range(n+1):
|
||||
fast = fast.next
|
||||
n -= 1
|
||||
while(fast!=None):
|
||||
|
||||
# 移动两个指针,直到快速指针到达链表的末尾
|
||||
while fast:
|
||||
slow = slow.next
|
||||
fast = fast.next
|
||||
#fast 走到结尾后,slow的下一个节点为倒数第N个节点
|
||||
slow.next = slow.next.next #删除
|
||||
return head_dummy.next
|
||||
|
||||
# 通过更新第 (n-1) 个节点的 next 指针删除第 n 个节点
|
||||
slow.next = slow.next.next
|
||||
|
||||
return dummy_head.next
|
||||
|
||||
```
|
||||
Go:
|
||||
```Go
|
||||
|
Reference in New Issue
Block a user