在 C++ 中查找两个单链表中的公共节点
假设我们有两个单链表。我们必须找到两个单链表中公有节点的总数。因此,如果两个链表像 [15, 16, 10, 9, 7, 17] 和 [15, 16, 40, 6, 9],则有三个公有节点。
使用两个嵌套循环遍历到链表尾部,对于链表中的每个节点,检查它是否与第二个链表的任何节点匹配。如果找到匹配项,则增加计数器,最后返回计数。
示例
#include<iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
};
void prepend(Node** start, int new_data) {
Node* new_node = new Node;
new_node->data = new_data;
new_node->next = NULL;
if ((*start) != NULL){
new_node->next = (*start);
*start = 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->next;
}
ptr1 = *start2;
ptr = ptr->next;
}
return count;
}
int main() {
Node* first = NULL;
Node* second = NULL;
prepend(&first, 15);
prepend(&first, 16);
prepend(&first, 10);
prepend(&first, 9);
prepend(&first, 7);
prepend(&first, 17);
prepend(&second, 15);
prepend(&second, 16);
prepend(&second, 40);
prepend(&second, 6);
prepend(&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