在 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

更新於: 2019-12-19

216 次瀏覽

啟動你的 職業生涯

完成課程取得認證

開始
廣告
© . All rights reserved.