#include <iostream>
#include <string>
using namespace std;
struct node {
int value;
node *next;
};
node *add_node(node *head, int value) {
node *new_node = new node();
new_node -> value = value;
new_node -> next = NULL;
node *p_node = new node();
p_node = head;
if(head == NULL)
head = new_node;
else {
while(p_node -> next != NULL) {
p_node = p_node -> next;
}
p_node -> next = new_node;
}
return head;
}
void print_common_part(node *head1, node *head2) {
while(head1 != NULL && head2 != NULL) {
if(head1 -> value < head2 -> value)
head1 = head1 -> next;
else if(head1 -> value > head2 -> value)
head2 = head2 -> next;
else {
cout << head1 -> value << ' ';
head1 = head1 -> next;
head2 = head2 -> next;
}
}
}
int main() {
node *head1 = NULL;
node *head2 = NULL;
string str, str_s;
cout << "please input the data of list1!" << endl;
getline(cin, str);
while(str.find(' ', 0) != string :: npos) {
head1 = add_node(head1, atoi(str.substr(0, str.find(' ', 0)).c_str()));
str.erase(0, str.find(' ', 0) + 1);
}
head1 = add_node(head1, atoi(str.c_str()));
cout << "please input the data of list2!" << endl;
getline(cin, str);
while(str.find(' ', 0) != string :: npos) {
head2 = add_node(head2, atoi(str.substr(0, str.find(' ', 0)).c_str()));
str.erase(0, str.find(' ', 0) + 1);
}
head2 = add_node(head2, atoi(str.c_str()));
cout << "the common part is: " << endl;
print_common_part(head1, head2);
system("pause");
return 0;
}
C++链表:打印两个有序链表的公共部分
最新推荐文章于 2021-02-21 11:01:42 发布