Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

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