例如:L=1,3,4 那么将P中第1,3,4个元素打印出来
#ifndef List
#include <iostream>
using namespace std;
struct listNode;
typedef int ElementType;
typedef struct listNode *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
int isEmpty(List head);
List creatList(int num);
void disPlay(List head);
void PrintLots(List Phead,List Lhead);
#endif
//定义链表结构体
struct listNode{
ElementType data;
Position next;
};
int main(){
List P,L;
int num=1;
//建立链表P
cout<<"链表P,请输入要存储的元素个数:"<<" ";
cin>>num;
P=creatList(num);
//建立链表L
cout<<"链表L,请输入要存储的元素个数:"<<" ";
cin>>num;
L=creatList(num);
//打印链表
cout<<"已建立的链表P:"<<" ";
disPlay(P);
cout<<endl;
cout<<"已建立的链表L:"<<" ";
disPlay(L);
cout<<endl;
cout<<"按要求打印: ";
PrintLots(P,L);
return 0;
}
//判断链表是否为空
int isEmpty(List head){
return head->next==NULL;
}
//带有头结点的尾部插入法创建链表
List creatList(int num){
ElementType elem;//链表中存储的元素
List head;
Position p,s;
head=(List)malloc(sizeof(listNode)); //创建头结点
p=head;
p->next=NULL;
cout<<endl;
for(int i=0,j=1;i<num;i++,j++){
cout<<"请输入第"<<j<<"个元素:"<<" ";
cin>>elem;
s=(List)malloc(sizeof(listNode));//创建链表节点
s->data=elem;
p->next=s;
p=s;
p->next=NULL;
cout<<endl;
}
return head;
}
//输出链表
void disPlay(List head){
if(isEmpty(head)){
cout<<"链表不存在";
}else{
List p;
p=head->next;
while(p){
cout<<p->data<<" ";
p=p->next;
}
}
}
//
void PrintLots(List Phead,List Lhead){
Position L,P;
ElementType elem,count=1;
L=Lhead->next;
P=Phead->next;
while(L){
elem=L->data;
while(elem!=count){
P=P->next;
count++;
}
if(P){
cout<<P->data<<" ";
L=L->next;
}
}
}