数据结构篇:单链表基础操作(二)

已知带头结点的单链表,存放一组整型数
①创建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;
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值