fork download
  1. #include <list>
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. // Function to find the intersection of two sorted lists
  6. std::list<int> intersection(const std::list<int>& l1, const std::list<int>& l2) {
  7. std::list<int> result; // Stores the common elements
  8. auto it1 = l1.begin(); // Iterator for l1
  9. auto it2 = l2.begin(); // Iterator for l2
  10.  
  11. // Traverse both lists using iterators
  12. while (it1 != l1.end() && it2 != l2.end()) {
  13. if (*it1 < *it2) {
  14. ++it1; // Move iterator of l1 forward
  15. } else if (*it2 < *it1) {
  16. ++it2; // Move iterator of l2 forward
  17. } else {
  18. // Both elements are equal, add to result
  19. result.push_back(*it1);
  20. ++it1;
  21. ++it2;
  22. }
  23. }
  24. return result; // Return the intersection list
  25. }
  26.  
  27. // Function to print a list
  28. void printList(const std::list<int>& lst) {
  29. std::cout << "{ ";
  30. for (int num : lst) {
  31. std::cout << num << " ";
  32. }
  33. std::cout << "}" << std::endl;
  34. }
  35.  
  36. // Main function
  37. int main() {
  38. // Test Case 1: {1, 2, 3, 4} ∩ {2, 3} = {2, 3}
  39. std::list<int> l1 = {1, 2, 3, 4};
  40. std::list<int> l2 = {2, 3};
  41. std::list<int> result1 = intersection(l1, l2);
  42.  
  43. std::cout << "Test Case 1: Intersection: ";
  44. printList(result1); // Expected Output: {2, 3}
  45. // Test Case 2: {2, 9, 14} ∩ {1, 7, 15} = {}
  46. std::list<int> l3 = {2, 9, 14};
  47. std::list<int> l4 = {1, 7, 15};
  48. std::list<int> result2 = intersection(l3, l4);
  49. std::cout << "Test Case 2: Intersection: ";
  50. printList(result2); // Expected Output: {}
  51.  
  52. // Test Case 3: Empty list ∩ {2, 3} = {}
  53. std::list<int> l5; // Empty list
  54. std::list<int> l6 = {2, 3};
  55. std::list<int> result3 = intersection(l5, l6);
  56.  
  57. std::cout << "Test Case 3 (Empty l1): Intersection: ";
  58. printList(result3); // Expected Output: {}
  59.  
  60. return 0;
  61. }
  62.  
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
Test Case 1: Intersection: { 2 3 }
Test Case 2: Intersection: { }
Test Case 3 (Empty l1): Intersection: { }