在 Python 中从列表末尾删除第 N 个节点
pythonserver side programmingprogramming更新于 2025/10/25 14:04:17
假设我们有一个链接列表。我们必须从列表末尾删除第 N 个节点,然后返回其头部。因此,如果列表为 [1, 2, 3, 4, 5, 6] 且 n = 3,则返回的列表将为 [1, 2, 3, 5, 6]。
为了解决这个问题,我们将遵循以下步骤 −
- 如果 head 之后没有节点,则返回 None
- front := head, back := head, counter := 0 and fount := false
- 当 counter <= n
- 如果 front 不存在,则将 flag 设置为 true,并退出循环
- front := front 的下一个,并将 counter 增加 1
- 当 front 存在时
- front := front 的下一个
- back := next of back
- 如果 flag 为 false,则
- temp := next of back
- next of back := next of temp
- next of temp := None
- 否则 head := next of head
- Return head
示例 (Python)
让我们看下面的实现,以便更好地理解 −
class ListNode:
def __init__(self, data, next = None):
self.val = data
self.next = next
def make_list(elements):
head = ListNode(elements[0])
for element in elements[1:]:
ptr = head
while ptr.next:
ptr = ptr.next
ptr.next = ListNode(element)
return head
def print_list(head):
ptr = head
print('[', end = "")
while ptr:
print(ptr.val, end = ", ")
ptr = ptr.next
print(']')
class Solution(object):
def removeNthFromEnd(self, head, n):
if not head.next:
return None
front=head
back = head
counter = 0
flag = False
while counter<=n:
if(not front):
flag = True
break
front = front.next
counter+=1
while front:
front = front.next
back = back.next
if not flag:
temp = back.next
back.next = temp.next
temp.next = None
else:
head = head.next
return head
head = make_list([1,2,3,4,5,6])
ob1 = Solution()
print_list(ob1.removeNthFromEnd(head, 3))
输入
[1,2,3,4,5,6] 3
输出
[1,2,3,5,6]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

