定义一个链表类List3,其结构中私有数据成员如下表:
对以上三个链表的具体要求如下:
1.定义构造函数和析构函数
2.输出数据成员函数 void display( );
3.返回链表长度函数 int Length( );
4.在链表尾追加一个节点,数据值为t, 返回值是在链表中的位置:
int Append( const Type &t);
5.在链表中的第i个位置插入一个节点,数据为t, 返回值表示是否成功
int Insert(const Type &t , int i);
6.将链表进行冒泡排序 void BubbleSort( );
7.在链表中检索数据值为t的节点,并返回其位置信息 int Search( Type &t );
8.对数组下标运算符重载,以实现对象对成员数组元素的访问 Type & operator [ ] (int i);
#includeusing namespace std; template class Node { public: Type Data; Node* next; }; template class List3 {//public Node { private: Node * head; int Length; public: void Get() { cout << head->next->Data< ; head->Data = -1; head->next = NULL; Length = 1; } int length() { return Length; } int Append(const Type& t) { Node * p,*q; p = head; while (p ->next!= NULL) { p = p->next; } q = new Node ; q->Data = t; q->next = NULL; p->next = q; Length++; return Length; } int Insert(const Type& t, int i) { Node * p, * q; p = head; for (int loc = 0; loc < i-1; loc++) { p = p->next; } q = new Node ; q->Data = t; q->next = p->next; p->next = q; Length++; return Length; } void BubbleSort() { for (int i = 0; i < Length; i++) { Node * p, * q; Type k; p = head; for (int j = 0; j < Length - 1; j++) { q = p->next; if (q->Data < p->Data) { k = p->Data; p->Data = q->Data; q->Data = k; } p = p->next; } } } int Search(Type& t) { Node * p; p = head; int i = 0; while(p != NULL) { i++; if (p->Data == t) { return i; } p = p->next; } return 0; } Type& operator [ ] (int i) { Node * p; p = head; for (int j = 0; j < i; j++) { p = p->next; } return p->Data; } void Display() { Node * p; p = head; while (p != NULL) { cout << p->Data << " "; p = p->next; } cout << endl; } }; int main() { List3 L; int n; //cin >> n; L.Append(70); L.Append(3); L.Append(5); L.Append(1); L.Append(8); L.Display(); L.BubbleSort(); L.Display(); L.Insert(55, 3); L.Display(); cout< 注:1:链表头赋值为-1,方便排序的进行,也更方便数据的存取
2:以上主函数代码均为测试代码,可以进行后续完善(如添加菜单)



