单链表求两个集合交集

#include

using namespace std;

template
struct node
{
t data;
node*next;
};
template
class linklist
{
public:
linklist(); //建立只有头结点的空链表
linklist(t a[],int n);//建立有n个元素的空链表
~linklist();
int length();
t get(int i);
int locate(t x);
void insert(int i,t x);
t Delete(int i);
void printlist();
private:
node*first; //单链表的头指针;
};
template
void linklist::printlist()
{
node *p;
p=first->next;
while(p!=NULL)
{
cout<data<<" “;
p=p->next;
}
cout<<endl;
};
template
int linklist::length()
{
node*p;
int count;
p=first->next;count=0;
while(p!=NULL)
{
p=p->next;
count++;
}
return count;
};
template
int linklist::locate(t x)
{
int count;
node*p;
p=first->next;count=1;
while(p!=NULL)
{
if(p->datax)return count;
p=p->next;
count++;
}
return 0;
};
template
void linklist::insert(int i,t x)
{
int count;
node *p;
node *s;
p=first;count=0;
while(p!=NULL&&count<i-1)
{
p=p->next;
count++;
}
if(p
NULL)throw"位置”;
else{
s=new node;s->data=x;
s->next=p->next;p->next=s;
}
};
template
linklist::linklist()
{
first=new node;
first->next=NULL;
};
template //头插法
linklist::linklist(t a[],int n)
{
node *s;
first=new node;first->next=NULL;
for(int i=0;i<n;i++)
{
s=new node;s->data=a[i];
s->next=first->next;first->next=s;
}
};

template
t linklist::Delete(int i)
{
t x;
int count;
node *p=first,*q;count=0;
while(p!=NULL&&count<(i-1))
{
p=p->next;
count++;
}
if(pNULL||p->nextNULL)throw"位置";
else{
q=p->next;x=q->data;
p->next=q->next;
delete q;
return x;
}
};
template
linklist::~linklist()
{
node *q;
while(first!=NULL)
{
q=first;
first=first->next;
delete q;
}
}
template
t linklist::get(int i)
{
node *p=first->next;
int j=1;
while (p && j<i)
{
p=p->next;
j++;
}
if (!p) throw “位置”;
else return p->data;
}
template
void ajb(linklist &A,linklist &B)
{
t x;
linklist c;
for(int i=1;i<=B.length();i++)
{
x=B.get(i);//cout<<x<<" "<<A.locate(x)<<endl;
if(A.locate(x)!=0)
{
// B.Delete(i);
c.insert(1,x);
}
}
c.printlist();
};
int main()
{
int a[5]={1,3,4,5,7};
linklist A(a,5);
A.printlist();
cout<<A.get(3)<<endl;
cout<<A.length()<<endl;
cout<<A.locate(3)<<endl;
A.insert(2,10);
A.printlist();
int b[4]={3,4,6,7};
linklist B(b,4);
B.printlist();
cout<<B.get(3)<<endl;
cout<<B.length()<<endl;
cout<<B.locate(3)<<endl;
B.insert(2,10);
B.printlist();
ajb(A,B);
return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值