c++ 打印两个链表得公共部分

题目:

给定两个有序链表的头指针 head1 和 head2,打印两个链表的公共部分。

左程云 代码 c++ 实现:

#include <iostream>
using namespace std;

struct node{
    int value;
    node *next;
};

void 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;
    }
}


void printcompart(node *head1, node* head2){

    while (head1 != NULL && head2 != NULL){
        if (head1->value > head2->value){
            head2 = head2->next;
        }
        else if (head1->value < head2->value){
            head1 = head1->next;
        }
        else{
            cout << head1->value << " ";
            head1 = head1->next;
            head2 = head2->next;
        }
    }
    cout << endl;
}
void display(node* head){
    node * p = head;
    while (p != NULL){
        cout << p-> value << " ";
        p = p->next;
    }
}

int main(){
    node* node1 = NULL;
    node* node2 = NULL;

    add_node(&node1, 2);
    add_node(&node1, 6);
    add_node(&node1, 8);
    display(node1);
    cout << endl;

    add_node(&node2, 2);
    add_node(&node2, 3);
    display(node2);

    cout << endl;
    cout << "the common part is :";
    printcompart(node1, node2);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你好,下面是用C++创建两个相交链表的示例代码: ```c++ #include <iostream> using namespace std; // 定义链表节点 struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; // 创建两个相交链表 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { ListNode *p1 = headA, *p2 = headB; while (p1 != p2) { // 遍历到链表末尾后,从另外一个链表头部继续遍历 p1 = p1 == nullptr ? headB : p1->next; p2 = p2 == nullptr ? headA : p2->next; } return p1; } int main() { // 创建第一个链表 ListNode *headA = new ListNode(1); ListNode *n1 = new ListNode(2); ListNode *n2 = new ListNode(3); ListNode *n3 = new ListNode(4); headA->next = n1; n1->next = n2; n2->next = n3; // 创建第二个链表 ListNode *headB = new ListNode(5); ListNode *m1 = new ListNode(6); ListNode *m2 = new ListNode(7); ListNode *m3 = n2; // 第二个链表从第一个链表的第三个节点开始相交 headB->next = m1; m1->next = m2; m2->next = m3; // 遍历两个链表验证相交 ListNode *intersectionNode = getIntersectionNode(headA, headB); if (intersectionNode != nullptr) { cout << "链表相交点为:" << intersectionNode->val << endl; } else { cout << "链表不相交" << endl; } return 0; } ``` 输出结果: ``` 链表相交点为:3 ``` 在这个例子中,我们创建了两个相交链表,然后通过 `getIntersectionNode` 函数遍历两个链表,找到它们的相交点,并返回相交点的指针。在主函数中,我们输出了相交点的值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值