C++链表:打印两个有序链表的公共部分

#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值