Python程序:移除链表中给定目标元素的最后一次出现
假设我们有一个单链表,还有一个名为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 := 节点
- k := null, prev := null
- found := False
- 当节点不为空时,执行以下操作:
- 如果节点的值与target相同,则:
- found := True
- prev := k
- k := node
- node := node 的下一个节点
- 如果节点的值与target相同,则:
- 如果found为False,则:
- 返回head
- 如果prev为空,则:
- 返回head的下一个节点
- prev的下一个节点 := 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, ]
广告