⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 9.16.cpp

📁 这是C++的一部分练习程序!对初学者有一定的帮助作用。
💻 CPP
字号:
#include <iostream.h>
class List;
//结点类
class Item
{
public:
	friend class List;  //友元类
private:
	Item(int d=0)
	{  data=d;next=0;  }
	Item *next;
	int data;
};
//链表类
class List  
{
public:
	List()
	{  list=0;  }
	List(int d)
	{  list=new Item(d);  }
	int Print();
	int Insert(int d=0);
	int Append(int d=0);
	void Cat(List &il);
	void Reverse();
	int Length();
private:
	Item *end();
	Item *list;
}; 
//输出函数
int List::Print()
{
	if(list==0)
	{
		cout<<"empty.\n";
		return 0;
	}
	cout<<'{';
	int cnt=0;
	Item *pt=list;
	while(pt)
	{
		if(++cnt%40==1&&cnt!=1)
			cout<<endl;
		cout<<pt->data<<' ';
		pt=pt->next;
	}
	cout<<"}\n";
	return cnt;
}
//插入结点函数
int List::Insert(int d)
{
	Item *pt=new Item(d);
	pt->next=list;
	list=pt;
	return d;
}
//追加结点函数
int List::Append(int d)
{
	Item *pt=new Item(d);
	if(list==0)
		list=pt;
	else
		(end())->next=pt;
	return d;
}
Item *List::end()
{
	Item *prv,*pt;
	for(prv=pt=list;pt;prv=pt,pt=pt->next)
		;
	return prv;
}
//连接链表函数
void List::Cat(List &il)
{
	Item *pt=il.list;
	while(pt)
	{
		Append(pt->data);
		pt=pt->next;
	}
}
//将链表结点逆向输出
void List::Reverse()
{
	Item *pt,*prv,*tmp;
	prv=0;
	pt=list;
	list=end();
	while(pt!=list)
	{
		tmp=pt->next;
		pt->next=prv;
		prv=pt;
		pt=tmp;
	}
	list->next=prv;
}
//求链表长度函数
int List::Length()
{
	int cnt=0;
	Item *pt=list;
	for(;pt;pt=pt->next,cnt++)
		;
	return cnt;
}
//主函数
void main()
{
	List list1;  //创建链表1
	list1.Print();
	for(int i=1;i<10;i++)
		list1.Insert(i);
	cout<<"list1: ";
	list1.Print();
	List list2;  //创建链表2
	for(i=15;i<25;i++)
		list2.Append(i);
	cout<<"list2: ";
	list2.Print();
	cout<<"list1 length: "<<list1.Length()<<endl;
	list2.Cat(list1);   //把链表1加到链表2的尾部
	cout<<"list2: ";
	list2.Print();
	list2.Reverse();  //把链表2结点反向输出
	cout<<"list2: ";
	list2.Print();
	cout<<"list2 length: "<<list2.Length()<<endl;
}


   

		

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -