十四周任務(二)

/* (程序頭部註釋開始)

* 程序的版權和版本聲明部分

* Copyright (c) 2011, 煙臺大學計算機學院學生

* All rights reserved.* 文件名稱:    000

* 作 者:   楊繼宇

* 完成日期: 2012年05 月21 日

* 版 本 號: 0000

* 對任務及求解方法的描述部分 

* 輸入描述:

* 問題描述:

* 程序輸出:

* 程序頭部的註釋結束

*/

#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 ()
{
	if (head=NULL)
	{
		cout<<"empty\n";
		return  0;
	}
	int c=0;
	Student *pt=head;
	while(pt)
	{++c;
	cout<< pt->num<< " " << pt->score<<endl;
	pt = pt->next;
	}
	return c;
}
void MyList::insert  (int n,double s )

{
	Student * pt=new Student(n,s);
	pt-> next=head;
	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)
{
	Student *pt=il.head ;
	while (pt)
	{
		append (pt->num,pt->score );
		pt=pt->next ;
	}
}
int MyList ::length ()
	{
		int c=0;
		Student *pt =head;
		while (pt)
		{
			++c;
			pt=pt->next ;
		}
		return c;
	}  


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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章