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):
|
# def __init__(self, val=0, next=None):
|
||||||
# self.val = val
|
# self.val = val
|
||||||
# self.next = next
|
# self.next = next
|
||||||
|
|
||||||
class Solution:
|
class Solution:
|
||||||
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
|
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
|
fast = fast.next
|
||||||
n -= 1
|
|
||||||
while(fast!=None):
|
# 移动两个指针,直到快速指针到达链表的末尾
|
||||||
|
while fast:
|
||||||
slow = slow.next
|
slow = slow.next
|
||||||
fast = fast.next
|
fast = fast.next
|
||||||
#fast 走到结尾后,slow的下一个节点为倒数第N个节点
|
|
||||||
slow.next = slow.next.next #删除
|
# 通过更新第 (n-1) 个节点的 next 指针删除第 n 个节点
|
||||||
return head_dummy.next
|
slow.next = slow.next.next
|
||||||
|
|
||||||
|
return dummy_head.next
|
||||||
|
|
||||||
```
|
```
|
||||||
Go:
|
Go:
|
||||||
```Go
|
```Go
|
||||||
|
Reference in New Issue
Block a user