假设我们有一个排序的双向链接的唯一正数列表;我们必须在双链表中找到对,它们的乘积与给定值x相同。我们必须记住,这将在不占用任何额外空间的情况下解决。
因此,如果输入像L = 1⇔2⇔4⇔5⇔6⇔8⇔9并且x = 8,则输出将是(1,8),(2,4)
为了解决这个问题,我们将遵循以下步骤-
curr:=头,nxt:=头
当nxt.next不为None不为零时,执行
nxt:= nxt.next
发现:=错误
当curr和nxt不为null并且curr和nxt不同并且nxt.next不是curr时
如果(curr.data * nxt.data)<x,则
除此以外,
curr:= curr.next
nxt:= nxt.prev
找到:=真
显示一对curr.data,nxt.data
curr:= curr.next
nxt:= nxt.prev
如果(curr.data * nxt.data)与x相同,则
除此以外,
如果发现为假,则
显示“未找到”
让我们看下面的实现以更好地理解-
class ListNode: def __init__(self, data): self.data = data self.prev = None self.next = None def insert(head, data): node = ListNode(0) node.data = data node.next = node.prev = None if (head == None): (head) = node else : node.next = head head.prev = node head = node return head def get_pair_prod(head, x): curr = head nxt = head while (nxt.next != None): nxt = nxt.next found = False while (curr != None and nxt != None and curr != nxt and nxt.next != curr) : if ((curr.data * nxt.data) == x) : found = True print("(", curr.data, ", ", nxt.data, ")") curr = curr.next nxt = nxt.prev else : if ((curr.data * nxt.data) < x): curr = curr.next else: nxt = nxt.prev if (found == False): print( "Not found") head = None head = insert(head, 9) head = insert(head, 8) head = insert(head, 6) head = insert(head, 5) head = insert(head, 4) head = insert(head, 2) head = insert(head, 1) x = 8 get_pair_prod(head, x)
head = None head = insert(head, 9) head = insert(head, 8) head = insert(head, 6) head = insert(head, 5) head = insert(head, 4) head = insert(head, 2) head = insert(head, 1) x = 8
输出结果
( 1 , 8 ) ( 2 , 4 )