第14周实验报告2

来源:互联网 发布:resolved java 编辑:程序博客网 时间:2024/05/17 18:16
/* (程序头部注释开始)        * 程序的版权和版本声明部分        * 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; //输出head1head1.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;   //输出head2head2.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 2223 3334 44head1:34  44      23  33      12  222 33 44 5head2:34  44      2  3      3  4      4  5length of head2 after cat:7head2 after cat:34  44      2  3      3  4      4  5      34  44      23  33      12  22      请按任意键继续. . .


 


 

原创粉丝点击