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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP