已知带头结点的单链表,存放一组整型数
①创建n个元素的单链表
②计算链表中值大于x的结点的个数,int countx(lnode *head,int x)
③两个链表ha,hb存放整型数,每个链表中无相同元素,hc=ha∩hb,即ha和hb中相同元素放入hc中,void intersection(lnode *ha,lnode *hb,lnode *&hc)
#include <iostream>
using namespace std;
typedef struct Link {
int num;
Link * next;
} Inode;
class Test {
public :
Inode * t_CreateList(Inode * Head,int n);//尾插法建立单链表
int Countx(Inode *Head,int x);
void Intersection(Inode *ha,Inode *hb,Inode *&hc);
void ShowLink(Inode *h);
};
Inode * Test:: t_CreateList(Inode * Head,int n) {
Inode *p = Head;
for(int i=0; i<n; i++) {
Inode * s = new Inode;
cin>>s->num;
s->next = p->next;
p->next = s;
p=s;
}
return Head;
}
int Test::Countx(Inode *Head , int x) {
Inode *p=Head;
int count= 0;
while(p->next) {
if(p->next->num > x) {
count++;
}
p = p->next;
}
return count;
}
void Test :: Intersection(Inode *ha,Inode *hb,Inode *&hc)
{
Inode * haTemp = ha,*hbTemp = hb,*hcTemp = hc;
while(haTemp->next)
{
hbTemp = hb;
while(hbTemp->next)
{
if(haTemp->next->num == hbTemp->next->num)
{
Inode * temp=new Inode;
temp->num = haTemp->next->num;
temp ->next = hcTemp->next;
hcTemp->next = temp;
hcTemp = temp;
}
hbTemp = hbTemp->next;
}
haTemp = haTemp->next;
}
}
void Test::ShowLink(Inode *h) {
Inode *p=h;
while(p->next) {
cout<<p->next->num<<endl;
p = p->next;
}
}
int main() {
Test test;
Inode *hb = new Inode,*hc = new Inode,* temp = new Inode ;
/*
下面三行是对头结点的下一节点进行置空
*/
temp->next = NULL;
hb->next = NULL;
hc->next = NULL;
int num;
cout<<"您想要创建及格元素的单链表?请输入:"<<endl;
cin>>num;
temp = test.t_CreateList(temp,num);
test.ShowLink(temp);
cout<<"您想要计算大于多少的结点的个数,请输入:"<<endl;
cin>>num;
cout<<"有"<<test.Countx(temp, num)<<"个大于"<<num<<"的元素。"<<endl;
cout<<"请再创建一个单链表与现在这个求交集,您想要创建及格元素的单链表?请输入:"<<endl;
cin>>num;
hb =test.t_CreateList(hb,num);
test.Intersection(temp,hb,hc);
test.ShowLink(hc);
return 0;
}