在 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