C++ 中排序雙向連結串列中計數三元組,其乘積等於給定值 x


給定一個包含整數值的排序雙向連結串列。目標是找到三元組,其乘積等於給定值 x。如果輸入連結串列為 3−4−1−2 且 x 為 6,則計數將為 1(三元組 (3,1,2))

例如

輸入

linked list: [ 200−4−16−5−10−10−2 ] x=200

輸出

Count of triplets in a sorted doubly linked list whose product is equal to a given
value x are: 3

解釋

Triplets will be:
(4,5,10), (4,5,10) and (10,10,2)

輸入

linked list: [ 4−3−1−5−2−4−2] x=12

輸出

Count of triplets in a sorted doubly linked list whose product is equal to a given
value x are: 3

解釋

Triplets will be:
(4,3,1), (3,1,4) and (3,2,2)

下面程式中使用的方案如下

在這種方法中。

  • 我們將連結串列節點作為結構體,包含 int 資料部分以及自引用 next 和 previous 指標。

  • 函式 insert_node(struct block** head, int data) 在連結串列頭部新增節點,並帶有資料。

  • 函式 Product_x(struct block* head, int x) 獲取雙向連結串列頭部的指標和整數 x,並返回具有資料部分乘積為 x 的節點的三元組的計數。

  • 將初始計數設定為 0。

  • 獲取三個型別為 struct block 的指標 temp_1、temp_2 和 temp_3。

  • 從 temp_1 指向連結串列頭部開始,temp_2 指向 temp_1 的下一個節點,temp_3 指向 temp_3 的下一個節點,我們有三個指標指向前三個節點。

  • 使用這些指標遍歷直到最後一個節點。

  • 如果所有上述指標的當前資料部分的乘積為 x。((temp_1−>data * temp_2− >data * temp_3−>data) == x),則遞增計數。

  • 最後,我們計算了三元組的數量並存儲在 count 中。

  • 返回 count 作為結果。

示例

 線上演示

#include <iostream>
using namespace std;
struct block{
   int data;
   struct block *next, *prev;
};
void insert_node(struct block** head, int data){
   struct block* ptr = new block();
   ptr−>data = data;
   ptr−>next = NULL;
   ptr−>prev = NULL;
   if ((*head) == NULL){
      (*head) = ptr;
   } else {
      ptr−>next = *head;
      (*head)−>prev = ptr;
      (*head) = ptr;
   }
}
int Product_x(struct block* head, int x){
   int count = 0;
   struct block *temp_1, *temp_2, *temp_3;
   for (temp_1 = head; temp_1!= NULL; temp_1 = temp_1−>next){
      for (temp_2 = temp_1−>next; temp_2 != NULL; temp_2 = temp_2−>next){
         for (temp_3 = temp_2−>next; temp_3!= NULL; temp_3 = temp_3−>next){
            if ((temp_1−>data * temp_2−>data * temp_3−>data) == x){
               count++;
            }
         }
      }
   }
   return count;
}
int main(){
   struct block* head = NULL;
   insert_node(&head, 200);
   insert_node(&head, 100);
   insert_node(&head, 16);
   insert_node(&head, 14);
   insert_node(&head, 10);
   insert_node(&head, 10);
   insert_node(&head, 2);
   int x = 200;
   cout<<"Count of triplets in a sorted doubly linked list whose product is equal to a given value
   x are: "<<Product_x(head, x);
   return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出 -

Count of triplets in a sorted doubly linked list whose product is equal to a given value x are : 1

更新於: 2021年1月5日

171 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.