简体   繁体   中英

Intersection of two Sorted Linked Lists C++

I have some troubles with my intersection method. It works properly, but after end of programm it throws mistakes. Here`s my code:

void SortedLinkedList::intersection(SortedLinkedList finalList, SortedLinkedList list1, SortedLinkedList list2) {
        Node *pointer1 = list1.first;
        Node *pointer2 = list2.first;
        int counter = 0;
        while (pointer1 != NULL && pointer2 != NULL) {
            if (pointer1->data < pointer2->data) {
                pointer1 = pointer1->next;
            }
            else if (pointer2->data < pointer1->data){
                pointer2 = pointer2->next;
            }
            else if (pointer1->data == pointer2->data){
                finalList.addItem(pointer1->data);
                pointer1 = pointer1->next;
                pointer2 = pointer2->next;
            }
        }
        finalList.printList();
    }

I need to get intersection of two lists in a third one.

Main glaring mistake: SortedLinkedList finalist You have to change values in that class, it's your output data structure. You have to pass it by reference, otherwise the actual list passed to the function never will be changed.

In some cases you would like other input data passed refs too, just if you do it with "const" declarator, you have to use only const methods from them. As you actually do not use any methods andyour class is relatively simple, that doesn't matter much

void SortedLinkedList::intersection(SortedLinkedList& finalList, 
                  const SortedLinkedList& list1,
                  const SortedLinkedList& list2) 

Anything else without seeing whole design of your class would be guesswork. problem might be in your AddItem method or in lack of class fields initialization.

The standard library offer a method for that std::set_intersection

It is precisely used to merge to sorted containers.

This is the snippet taken from the link:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
  std::vector<int> v1{1,2,3,4,5,6,7,8};
  std::vector<int> v2{        5,  7,  9,10};
  std::sort(v1.begin(), v1.end());
  std::sort(v2.begin(), v2.end());

  std::vector<int> v_intersection;

  std::set_intersection(v1.begin(), v1.end(),
                        v2.begin(), v2.end(),
                        std::back_inserter(v_intersection));
  for(int n : v_intersection)
    std::cout << n << ' ';
}

In the link you will find a couple of possible implementations as well. But, my suggestion is: "Don't reinvent the wheel, just realign it".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM