1. 程式人生 > >資料結構篇:單鏈表基礎操作(二)

資料結構篇:單鏈表基礎操作(二)

已知帶頭結點的單鏈表,存放一組整型數 ①建立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;
}