用 Python 编写的程序,用于从链接列表中删除给定目标的最后一次出现
pythonserver side programmingprogramming
假设我们有一个单链表,还有另一个名为 target 的值,我们必须删除给定列表中最后一次出现的 target。
因此,如果输入为 [5,4,2,6,5,2,3,2,4,5,4,7],target = 5,则输出为 [5, 4, 2, 6, 5, 2, 3, 2, 4, 4, 7, ]
为了解决这个问题,我们将遵循以下步骤 −
- head := node
- k := null, prev := null
- found := False
- 当 node 不为 null 时,执行
- 如果 node 的值为与目标相同,则
- found := True
- prev := k
- k := node
- node := next of node
- 如果 node 的值为与目标相同,则
- 如果 found 为 False,则
- 返回 head
- 如果 prev 为 null,则
- 返回 next of head
- nect of prev := next of the next of prev
- 返回 head
让我们看看下面的实现以便更好地理解 −
示例
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:
def solve(self, node, target):
head = node
k = None
prev = None
found = False
while node:
if node.val == target:
found = True
prev = k
k = node
node = node.next
if found == False:
return head
if not prev:
return head.next
prev.next = prev.next.next
return head
ob = Solution()
L = make_list([5,4,2,6,5,2,3,2,4,5,4,7])
target = 5
print_list(ob.solve(L, target))
输入
[5,4,2,6,5,2,3,2,4,5,4,7]
输出
[5, 4, 2, 6, 5, 2, 3, 2, 4, 4, 7, ]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

