王道数据结构p40——14
代码
#include<stdio.h>
#include<stdlib.h>
typedef struct lnode{
int data;
lnode *next;
}lnode,*linklist;
void get_com(linklist &l,linklist &l2,linklist &c);
void printlink(linklist &l);
void creat(linklist &l,int a[],int n);
int main(){
linklist l;
linklist l2;
linklist c;
l = (lnode*)malloc(sizeof(lnode));
l->next = NULL;
l2 = (lnode*)malloc(sizeof(lnode));
l2->next = NULL;
c = (lnode*)malloc(sizeof(lnode));
c->next = NULL;
int a[10] = {1,2,3,4,5,6,7,8,9,10};
int b[10] = {0,1,4,5,6,8,10,11,25,36};
creat(l,a,10);
creat(l2,b,10);
get_com(l,l2,c);
printlink(c);
return 0;
}
void get_com(linklist &l,linklist &l2,linklist &c){
lnode *p,*q,*s,*r=c;
p = l->next;
q = l2->next;
while(q!=NULL && p!=NULL){
if(q->data > p->data){
p=p->next;
}
if(q->data < p->data){
q=q->next;
}
if(q->data == p->data){
s = (lnode*)malloc(sizeof(lnode));
s->data = q->data;
r->next = s;
r=s;
p=p->next;
q=q->next;
}
}
r->next = NULL;
}
void printlink(linklist &l){
lnode *s=l->next;
while(s!=NULL){
printf("%d\n",s->data);
s=s->next;
}
}
void creat(linklist &l,int a[],int n){
lnode *s,*p;
s=l;
for(int i=0;i<n;i++){
p = (lnode*)malloc(sizeof(lnode));
p->data = a[i];
s->next = p;
s=p;
}
s->next = NULL;
}
结果