6.7 应用实例——链表
在前面的章节中,我们已经学习了类和对象的基本知识和操作。为了更好地掌握这些知识,我们需要多阅读和编写程序,以提高编程技巧和能力。下面我们将通过一个单向链表的例子,展示如何使用类和对象实现常见的链表操作。
链表项和链表类
我们将先创建一个链表项类 Item
,它包含两个成员:一个数据项 data
和一个指针 next
,用于指向下一个链表项。然后,我们将创建一个链表类 List
,它包含多个链表操作,如显示链表、插入和追加链表项、连接链表、逆向输出链表项和计算链表长度。
链表项类 Item
#include <iostream>
using namespace std;
class List;
class Item {
public:
friend class List;
private:
Item(int d = 0) : data(d), next(0) {}
Item *next;
int data;
};
链表类 List
class List {
public:
List() : list(0) {}
List(int d) { list = new Item(d); }
int print();
int insert(int d = 0);
int append(int d = 0);
void cat(List &il);
void reverse();
int length();
private:
Item* end();
Item *list;
};
链表类的成员函数实现
显示链表
int List::print() {
if (list == 0) {
cout << "empty\n";
return 0;
}
cout << "(";
int cnt = 0;
Item *pt = list;
while (pt) {
if (cnt % 10 == 0 && cnt != 0) cout << endl;
cout << pt->data << " ";
pt = pt->next;
cnt++;
}
cout << ")\n";
return cnt;
}
插入链表项
int List::insert(int d) {
Item *pt = new Item(d);
pt->next = list;
list = pt;
return d;
}
追加链表项
int List::append(int d) {
Item *pt = new Item(d);
if (list == 0)
list = pt;
else
(end())->next = pt;
return d;
}
Item* List::end() {
Item *prv, *pt;
for (prv = pt = list; pt; prv = pt, pt = pt->next);
return prv;
}
连接两个链表
void List::cat(List &il) {
Item *pt = il.list;
while (pt) {
append(pt->data);
pt = pt->next;
}
}
逆向输出链表项
void List::reverse() {
Item *pt, *prv, *tmp;
prv = 0;
pt = list;
list = end();
while (pt != list) {
tmp = pt->next;
pt->next = prv;
prv = pt;
pt = tmp;
}
list->next = prv;
}
计算链表长度
int List::length() {
int cnt = 0;
Item *pt = list;
for (; pt; pt = pt->next, cnt++);
return cnt;
}
主函数
int main() {
List list1;
list1.print();
for (int i = 10; i < 18; i++)
list1.insert(i);
cout << "list1:";
list1.print();
List list2;
for (int i = 15; i < 20; i++)
list2.append(i);
cout << "list2:";
list2.print();
cout << "list1 length: " << list1.length() << endl;
list2.cat(list1);
cout << "list2:";
list2.print();
list2.reverse();
cout << "list2:";
list2.print();
cout << "list2 length: " << list2.length() << endl;
return 0;
}
执行上述程序,输出结果如下:
empty
list1:(17 16 15 14 13 12 11 10 )
list2:(15 16 17 18 19 )
list1 length: 8
list2:(15 16 17 18 19 17 16 15 14 13 12 11 10 )
list2:(10 11 12 13 14 15 16 17 19 18 17 16 15 )
list2 length: 13
总结
通过这个链表程序,我们实现了以下操作:
- 显示链表
- 插入链表项
- 追加链表项
- 连接两个链表
- 逆向输出链表项
- 计算链表长度
该程序应用了类和对象的许多基本知识,如类的定义、对象的定义、构造函数及其重载、子对象指针、友元类以及使用 new
动态创建对象。这些操作为编写更复杂的链表操作打下了基础。如果有兴趣,读者可以进一步完善该程序,添加删除、修改和查询功能。