1. 程式人生 > >鏈表 | 將遞增有序的兩個鏈表的公共元素合並為新的鏈表

鏈表 | 將遞增有序的兩個鏈表的公共元素合並為新的鏈表

body 鏈表 class std opened 有序 pri 新的 bsp

王道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指針滑動。在白紙上編寫時我忽略了這步。

鏈表 | 將遞增有序的兩個鏈表的公共元素合並為新的鏈表