C++ implements the method of printing the public parts of two ordered lists

  • 2020-05-19 05:14:16
  • OfStack

This article illustrates an example of how C++ can print the public parts of two ordered lists. I will share it with you for your reference as follows:

Topic:

Given the head Pointers head1 and head2 of two ordered lists, print the common parts of both lists.

Solution ideas and codes:

1. If the value of head1 is less than head2, then head1 moves down
2. If the value of head1 is less than head2, then head2 moves down
3. If it is equal, the value of any one list node will be printed, head1 and head2 will be moved down.
4. When head1 or head2 moves to NULL, it terminates.

Algorithm C++ code:


typedef struct Node
{
  int data;
  struct Node* next;
}node, *pLinkedlist;
void printCommomElem(pLinkedlist head1, pLinkedlist head2)
{
  cout << "print commom elements: " << endl;
  while (head1->next != NULL && head2->next != NULL)
  {
    if (head1->data < head2->data)
      head1 = head1->next;
    else if (head1->data > head2->data)
      head2 = head2->next;
    else
    {
      cout << head1->data << " ";
      head1 = head1->next;
      head2 = head2->next;
    }
  }
  cout << endl;
}

I hope this article has helped you with C++ programming.


Related articles: