第十四周任务(二)

建立自己的链表

 

#include<iostream>
using namespace std;
class Student
{                          
public:
	Student(int n,double s){num=n;score=s;next=NULL;}
	Student *next;
	int num;
	double score;
};

class MyList
{
public:
	MyList(){head=NULL;}
	MyList(int n,double s){head=new Student(n,s);} //以Student(n,s)作为单结点的链表
	int display();  //输出链表,返回值为链表中的结点数
	void insert(int n,double s);  //插入:将Student(n,s)结点插入链表,该结点作为第一个结点
	void append(int n,double s);  //追加:将Student(n,s)结点插入链表,该结点作为最后一个结点
	void cat(MyList &il); //将链表il连接到当前对象的后面
	int length();  //返回链表中的结点数
private:
	Student *head;
};

int MyList::display()        //输出链表,返回值为链表中的接点数。
{
	Student *p = head;
	if(p->next == NULL)
	{
		cout<<"出现错误"<<endl;
		return 0;
	}
	else
	{
		int i = 0;
		for(i;p!=NULL;i++)
		{
			
			cout<<"学号"<<p->num<<"    ";
			cout<<"分数"<<p->score<<endl;
			p = p->next;
				
		}
			
		return i;
	}
}

void MyList::insert(int n,double s)
{
	Student * pt=new Student(n,s);
	pt-> next=head;
	pt->num = n;
	pt->score = s;
	head = pt;
}

void MyList::append(int n,double s)

{
	Student * pt =new Student (n,s);
	if (head==NULL)
		head=pt ;
	else
	{
		Student *pts = head;
		Student *pte = pts -> next ;
		while (pte)
		{
			pts = pte;
			pte = pts -> next ;
		}
		pts -> next = pt;
	}
}

void MyList::cat(MyList &il)//将链表il连接到当前对象的后面
							/*{
							if(head->next=NULL)
							head->next = il.head;
}*/
{
	Student *pt=il.head ;
	while (pt)
	{
		append (pt->num,pt->score );
		pt=pt->next ;
	}
	
}
int MyList::length()  //返回链表中的结点数
{
    Student *p = head;
	int i = 0;
	for(i;;i++)
	{
		if(p->next ==NULL)
		{
			break;
        }
        p = p->next;
	}
	return i;
}





int main()
{
	int n;
	double s;
	MyList head1;
	cout<<"input head1: "<<endl;  //输入head1链表
	for(int i=0;i<3;i++)
	{
		cin>>n>>s;
		head1.insert(n,s);  //通过“插入”的方式
	}
	cout<<"head1: "<<endl; //输出head1
	head1.display();
	
	MyList head2(1001,98.4);  //建立head2链表
	head2.append(1002,73.5);  //通过“追加”的方式增加结点
	head2.append(1003,92.8);
	head2.append(1004,99.7);
	cout<<"head2: "<<endl;   //输出head2
	head2.display();
	
	head2.cat(head1);   //反head1追加到head2后面
	cout<<"length of head2 after cat: "<<head2.length()<<endl;
	cout<<"head2 after cat: "<<endl;   //显示追加后的结果
	head2.display();
	
	system("pause");
	return 0;
}


 

 

建立动态链表:可以给它定义一个类来储存数据以及next指针。例如:Student *p = head、这是类似使用类的对象时this指针吧。我认为head其实也可不比进行赋值,

                            也可以直接使用head = head->next。这样只是为了表示更清楚。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值