Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- //struct for each separate node
- struct Node {
- int data;
- Node* next;
- //constructor
- Node(int value) {
- data = value;
- next = nullptr;
- }
- };
- //struct for the linked list
- struct LinkedList {
- Node* head;
- //constructor
- LinkedList() {
- head = nullptr;
- }
- void insert(int value) {
- Node* newNode = new Node(value);
- if (head == nullptr) {
- head = newNode; //create head node
- }
- else {
- Node* current = head;
- //while the next element in list exists
- while (current->next != nullptr) {
- current = current->next;
- }
- current->next = newNode; //updates the next pointer to the current node
- }
- }
- void display() {
- Node* current = head;
- while (current != nullptr) {
- std::cout << current->data << " -> ";
- current = current->next;
- }
- std::cout << "nullptr" << std::endl;
- }
- void findCommonElements(LinkedList& otherList) {
- Node* current1 = head;
- while (current1 != nullptr) {
- int element = current1->data;
- Node* current2 = otherList.head;
- while (current2 != nullptr) {
- if (element == current2->data) {
- std::cout << "Common Element: " << element << std::endl;
- }
- current2 = current2->next;
- }
- current1 = current1->next;
- }
- }
- };
- int main()
- {
- LinkedList myList1, myList2;
- int n;
- std::cout << "Enter the number of values to insert: ";
- std::cin >> n;
- std::cout << "List 1\n";
- for (int i = 0; i < n; i++) {
- int value;
- std::cout << "Enter a value: ";
- std::cin >> value;
- myList1.insert(value); //Call the insert function
- }
- std::cout << "List 2\n";
- for (int i = 0; i < n; i++) {
- int value;
- std::cout << "Enter a value: ";
- std::cin >> value;
- myList2.insert(value); //Call the insert function
- }
- for (int i = 0; i < n; i++) {
- }
- std::cout << "List 1: ";
- myList1.display(); // Call the display function
- std::cout << "List 2: ";
- myList2.display();
- std::cout << "Common elements between the two lists: " << std::endl;
- myList1.findCommonElements(myList2);
- }
Advertisement
Add Comment
Please, Sign In to add comment