zoukankan      html  css  js  c++  java
  • 链表 | 将递增有序的两个链表的公共元素合并为新的链表

    王道P38T14

    主代码:

    LinkList common_subList(LinkList &A,LinkList &B){
        LNode *C=new LNode,*pC=C;
        C->next=NULL;
        LNode* pA=A->next,*pB=B->next;
        while(pA!=NULL && pB!=NULL){
            if(pA->data < pB->data){
                pA=pA->next;
            }else if(pA->data == pB->data){
                pC->next=new LNode;
                pC->next->data=pA->data;
                pC=pC->next;
                pC->next=NULL;
                pA=pA->next;
                pB=pB->next;
            }else{
                pB=pB->next;
            }
        }
        return C;
    } 

    完整代码:

    #include <cstdio>
    #include <stdlib.h>
    
    using namespace std;
    
    typedef struct LNode{
        int data;
        struct LNode* next=NULL; 
        LNode(){    }
        LNode(int x){    
            data=x;
        }
    }LNode;
    
    typedef LNode* LinkList;
    
    LinkList  build_list(int * arr,int n){
        int i;
        LinkList L=new LNode;
        LinkList pre=L;
        for(i=0;i<n;i++){
            LinkList p=new LNode(arr[i]);
            pre->next=p;
            pre=p;
        }
        return L;
    }
    
    void show_list(LinkList& L){
        LinkList p=L->next;
        while(p){
            printf("%d ",p->data);
            p=p->next;
        }
        puts("");
    }
    
    LinkList common_subList(LinkList &A,LinkList &B){
        LNode *C=new LNode,*pC=C;
        C->next=NULL;
        LNode* pA=A->next,*pB=B->next;
        while(pA!=NULL && pB!=NULL){
            if(pA->data < pB->data){
                pA=pA->next;
            }else if(pA->data == pB->data){
                pC->next=new LNode;
                pC->next->data=pA->data;
                pC=pC->next;
                pC->next=NULL;
                pA=pA->next;
                pB=pB->next;
            }else{
                pB=pB->next;
            }
        }
        return C;
    } 
    
    int main(){
        int A_arr[5]={1,2,3,5,9};
        int B_arr[5]={0,2,2,6,9};
        LinkList A=build_list(A_arr,5);
        LinkList B=build_list(B_arr,5);
        LinkList C=common_subList(A,B);
        show_list(A);
        show_list(B);    
        show_list(C);
    }
     
    View Code

    注意:

    要注意紫色代码处的pC指针滑动。在白纸上编写时我忽略了这步。

  • 相关阅读:
    python字符串的常用方法
    python基础之数据类型
    python自定义带参数和不带参数的装饰器
    python中logging结合pytest打印日志
    本地的项目上传到gitee仓库步骤--适合小白上手
    Python中的分数运算
    2018年6月23日开通我的Python学习博客
    python多版本兼容性问题:当同时安装Python2和Python3后,如何兼容并切换
    github之关联远程仓库
    SHH验证
  • 原文地址:https://www.cnblogs.com/TQCAI/p/8452028.html
Copyright © 2011-2022 走看看