/*
* author:王昌帅(山东科技大学)
* email:415939252@qq.com
* date :2012.11.29
*/
#include <iostream>
using namespace std;
typedef struct LNode
{
int data;
struct LNode* next;
}LNode,*LinkList;
/*
* 题目:14 p36
* 功能:得到两链表的共同元素,并以链表的形式返回
*/
LinkList getCommon(LinkList list1,LinkList list2)
{
LinkList list;
LNode *p,*q,*r,*node;
list = (LinkList)malloc(sizeof(LNode));
list->next = NULL;
r = list;
for(p = list1->next;p;p=p->next)
{
for(q = list2->next;q&&q->data <= p->data;q=q->next)
{
if(p->data == q->data)
{
node = (LNode*)malloc(sizeof(LNode));
node->data = p->data;
r->next = node;
r = node;
}
}
}
r->next = NULL;
return list;
}
int main()
{
int i ,temp,num;
LNode* node,*p;
LinkList list,list1,list2;
list1 = (LinkList)malloc(sizeof(LNode)); //头结点一定要开辟出来
list2 = (LinkList)malloc(sizeof(LNode)); //头结点一定要开辟出来
printf("请输入链表1中的元素个数:");
scanf("%d",&num);
printf("请递增输入:");
p = list1;
for(i = 0;i<num;i++)
{
scanf("%d",&temp);
node = (LNode*)malloc(sizeof(LNode));
node->data = temp;
p->next = node;
p = node;
}
p->next=NULL;
printf("请输入链表2中的元素个数:");
scanf("%d",&num);
printf("请递增输入:");
p = list2;
for(i = 0;i<num;i++)
{
scanf("%d",&temp);
node = (LNode*)malloc(sizeof(LNode));
node->data = temp;
p->next = node;
p = node;
}
p->next=NULL;
list = getCommon(list1,list2);
for(p=list->next;p;p = p->next)
{
printf(" %d",p->data);
}
printf("\n");
return 0;
}