C++中计算排序双向链表中和等于给定值x的三元组个数
给定一个包含整数值的排序双向链表。目标是找到乘积等于给定值x的三元组。如果输入链表是3-4-1-2,而x是6,则计数将为1(三元组(3,1,2))

例如
输入
linked list: [ 3−4−13−5−10−10−0 ] x=20
输出
Count of triplets in a sorted doubly linked list whose product is equal to a given value x are: 2
解释
Triplets will be: ( 3,4,13 ) and ( 10,10,0 )
输入
linked list: [ 4−3−1−5−2−4−2 ] x=8
输出
Count of triplets in a sorted doubly linked list whose product is equal to a given value x are: 6
解释
Triplets will be: ( 4,3,1), (1,5,2), (3,1,4), (1,5,2), (4,2,2) and (2,4,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_2的下一个节点,我们有三个指针指向前三个节点。
使用这些指针遍历到最后一个节点。
如果上述所有指针的当前数据部分的乘积为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 sum_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 = 22;
cout<<"Count of triplets in a sorted doubly linked list whose sum is equal to a given value x
are: "<<sum_x(head, x);
return 0;
}输出
如果我们运行上述代码,它将生成以下输出:
Count of triplets in a sorted doubly linked list whose sum is equal to a given value x are: 1
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP