码迷,mamicode.com
首页 > 其他好文 > 详细

链表 | 将递增有序的两个链表的公共元素合并为新的链表

时间:2018-02-17 18:07:39      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:common   分享图片   span   图片   class   hid   技术分享   turn   splay   

王道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指针滑动。在白纸上编写时我忽略了这步。

 

链表 | 将递增有序的两个链表的公共元素合并为新的链表

标签:common   分享图片   span   图片   class   hid   技术分享   turn   splay   

原文地址:https://www.cnblogs.com/TQCAI/p/8452028.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!