在 C++ 中查找两个双向链表中公共节点的数量
假设我们有两个双向链表。我们需要找出这两个双向链表中共有多少个公共节点。如果两个链表为 [15, 16, 10, 9, 7, 17] 和 [15, 16, 40, 6, 9],那么就存在三个公共节点。
使用两个嵌套循环来遍历两个链表直到末尾,对于链表中的每个节点,检查它是否与第二个链表中的任何节点匹配。如果找到匹配,则增加计数器,最后返回计数。
示例
#include<iostream>
using namespace std;
class Node {
public:
int data;
Node *back, *front;
};
void append(Node** start, int new_data) {
Node* new_node = new Node;
new_node->data = new_data;
new_node->back = NULL;
new_node->front = (*start);
if ((*start) != NULL)
(*start)->back = new_node;
(*start) = new_node;
}
int countCommonNodes(Node** start1, Node** start2) {
Node* ptr = *start1;
Node* ptr1 = *start2;
int count = 0;
while (ptr != NULL) {
while (ptr1 != NULL) {
if (ptr->data == ptr1->data) {
count++;
break;
}
ptr1 = ptr1->front;
}
ptr1 = *start2;
ptr = ptr->front;
}
return count;
}
int main() {
Node* first = NULL;
Node* second = NULL;
append(&first, 15);
append(&first, 16);
append(&first, 10);
append(&first, 9);
append(&first, 7);
append(&first, 17);
append(&second, 15);
append(&second, 16);
append(&second, 40);
append(&second, 6);
append(&second, 9);
cout << "Number of common nodes:" << countCommonNodes(&first, &second);
}输出
Number of common nodes:3
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP