#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;
int n = 0;
p = head;
while(p != NULL)
{
cout << p-> num << " " << p->score << endl;
p = p->next;
++n;
}
return n;
}
void MyList::insert(int n, double s) //插入:將Student(n,s)結點插入鏈表,該結點作爲第一個結點
{
Student *p = head;
head = new Student(n, s);
head->next = p;
}
void MyList::append(int n, double s) //追加:將Student(n,s)結點插入鏈表,該結點作爲最後一個結點
{
Student *p = head;
while (p->next != NULL)
{
p = p->next;
}
p->next = new Student(n, s);
}
void MyList::cat(MyList &il) //將鏈表il連接到當前對象的後面
{
Student *p = head;
while (p->next != NULL)
{
p = p->next;
}
p->next = il.head;
}
int MyList::length() //返回鏈表中的結點數
{
int n = 0;
Student *p = head;
while (p->next != NULL)
{
p = p->next;
++n;
}
return n;
}
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;
}
input head1:
e
head1:
-858993460 -9.25596e+061
-858993460 -9.25596e+061
-858993460 -9.25596e+061
head2:
1001 98.4
1002 73.5
1003 92.8
1004 99.7
length of head2 after cat: 6
head2 after cat:
1001 98.4
1002 73.5
1003 92.8
1004 99.7
-858993460 -9.25596e+061
-858993460 -9.25596e+061
-858993460 -9.25596e+061
請按任意鍵繼續. . .
上週網速不行。。沒有按時提交。。特此補上