力扣 19. 删除链表的倒数第 N 个结点

预置

1
2
3
4
5
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next

链表基本操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def removeNthFromEnd(head, n):
if not head: return
node_len, node_cur = 0, head
while node_cur:
node_cur = node_cur.next
node_len += 1

top = ListNode(next=head)

left_n, cur = node_len - n, top
# print(node_len, left_n)

while left_n > 0:
cur = cur.next
left_n -= 1

# print(cur.val)
cur.next = cur.next.next

return top.next
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2022 eightyninth
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信