现在的位置: 首页 > 综合 > 正文

第14周实验报告2

2013年10月24日 ⁄ 综合 ⁄ 共 1926字 ⁄ 字号 评论关闭
/* (程序头部注释开始)        
* 程序的版权和版本声明部分        
* Copyright (c) 2011, 烟台大学计算机学院学生         
* All rights reserved.        
* 文件名称:动态链表                                   
* 作    者:张旭                                      
* 完成日期:  2012   年   5   月   22  日        
* 版 本 号:略                   
* 对任务及求解方法的描述部分        
* 输入描述:略         
* 问题描述:略         
* 程序输出:略         
* 程序头部的注释结束        
*/

#include <iostream>
using namespace std;


template <class T>
class Node
{     
public:
	Node():next(NULL){}
	Node *next;
	T data;
};

template <class T>
class MyList
{
public:
	int display() 
	{
		Node<T> *a = head;
		int i = 0;
		for (;a->next != NULL; ++i)
		{
			cout << a->data << "  ";
			a = a->next;
		}
		cout << a->data << "  ";
		return i + 1;
	}
	void firstinsert(Node<T> &a) 
	{
		Node<T>* node = new Node<Student> (a);
		if (head == NULL)
		{
			head = node;
		}
		else
		{
		    node->next = head;
		    head = node;
		}
	}

	void append(Node<T> & b)
	{
		Node<T>* node = new Node<Student> (b);
		Node<T> *a = head;
		for (int i = 0; a->next != NULL; ++i)
		{
			a = a->next;
		}
		a->next = node;
	}

	MyList()
	{
		head=NULL;
	}

	MyList(Node<T> a)
	{
		head = new Node<T> (a);
	} 

	void cat(MyList &il)
	{
		Node<T> *a = head;
		for (int i = 0; a->next != NULL; ++i)
		{
			a = a->next;
		}
		a->next = il.head;
	}

	int length()
	{
		Node<T> *a = head;
		int i = 0;
		for (; a->next != NULL; ++i)
		{
			a = a->next;
		}
		return i + 1;
	}

	Node<T>* headarr ()
	{
		return this->head;
	}

private:
	Node<T> *head;
};

class Student
{                          
public:
	Student(int n = 0, double s = 0):num(n), score(s){}
	int num;
	double score;

	friend ostream& operator << (ostream & out, Student &A);
};


ostream& operator << (ostream & out, Student &A)
{
	out << A.num << "  " << A.score << "    ";
	return out;
}


int main()
{
	int n;
	double s;
	MyList<Student> head1;
	Node<Student> node;

	cout<<"input head1: "<<endl;  //输入head1链表
	for(int i=0;i<3;i++)
	{
		cin>>n>>s;
		node.data.num = n;
		node.data.score = s;//通过“插入”的方式
		head1.firstinsert(node);
	}
	cout<<"head1: "<<endl; //输出head1
	head1.display();
	cout << endl;

	Node<Student> nod;
	MyList<Student> head2(node);  //建立head2链表
	for(int i=0;i<3;i++)
	{
		cin>>n>>s;
		node.data.num = n;
		node.data.score = s;
		head2.append(node);
	}
	cout<<"head2: "<<endl;   //输出head2
	head2.display();
	cout << endl;

	head2.cat(head1);   //反head1追加到head2后面
	cout<<"length of head2 after cat: "<< endl << head2.length() << endl;
	cout<<"head2 after cat: "<<endl;   //显示追加后的结果
	head2.display();

	system("pause");
	return 0;
}

运行结果:

input head1:
12 22
23 33
34 44
head1:
34  44      23  33      12  22
2 3
3 4
4 5
head2:
34  44      2  3      3  4      4  5
length of head2 after cat:
7
head2 after cat:
34  44      2  3      3  4      4  5      34  44      23  33      12  22      请
按任意键继续. . .

 

 

抱歉!评论已关闭.