链表
链表是一种很常见的数据结构,通过对链表的相关操作,可以了解:
指针的作用,
函数的传参规则,
读取文本和写入文本。
一、引入库和函数
代码如下(示例):
#include<iostream>
#include<fstream>//读取文件和写入文件
using namespace std;
struct ListNode { //链表的结构,一系列数据和一个指针,
int value;
ListNode* next;//用于指向后继节点
ListNode(int valuel=0, ListNode* nextl = nullptr) { //对链表节点初始化,有两种调用方式,第一种无参,value默认为0,后继指针指向空。第二种有参,然后就赋值了。
value = valuel; next = nextl;
}
};
void cinlist(ListNode*& numberList) { //对链表进行手动输入
//为什么引用,是因为我们不仅改变指针所指对象的值,还要改变指针所指的对象。
decltype(numberList->value) number;//等价于int number;用于推断value的类型
cout << "请依次输入链表的值,输入-1终止" << endl;
while (cin >> number && number != -1) { //链表赋值
numberList = new ListNode(number, numberList);//新建一个链表节点,numberList指向这个节点,存储number和前一个numberList指针。
}
}
void printflist(ListNode* numberList) { //不需要改变指针所指对象,所以不加引用。
while (numberList != nullptr) { //打印链表,读入和输出是相反的。
cout << numberList->value << " ";
numberList = numberList->next;
}
}
void deletelist(ListNode*& numberList) { //这里delete没有关系,进程结束会自动回收内存,但是如果进程还在进行,内存需要delete。
ListNode* numberList1 = nullptr;//不能delete和访问下一个指针同时进行,所以需要一个临时指针。
while (numberList != nullptr) { //释放链表
numberList1 = numberList->next;
delete numberList;
numberList = numberList1;
}
}
void cinlisttxt(ListNode*& numberList,string a,string b) {
ifstream numberFile(a);//将文件名a的文件读入到numberFile输入流。
ofstream tt(b);
if (!numberFile) { //如果没有文件,就不能打开,注意新建一个文本文件
cout << "Error in opening the file of numbers." << endl;;
exit(1);
}
int number;
cout << "The contents of the file are: " << endl;
while (numberFile >> number && number != -1) {
cout << number << " ";
numberList = new ListNode(number, numberList);
tt << number << " ";//写入tt.txt
}
cout << endl;
}
主函数:
void main() {
ListNode* head = nullptr;
head = new ListNode;
head->value = 12;
head->next = nullptr;
ListNode* secondptr = new ListNode;
secondptr->value = 13;
secondptr->next = nullptr;
head->next = secondptr;
cout << head->value << '\n' << head->next->value << endl;//直接的上古依次输入链表的值
delete head; head = nullptr;
delete secondptr; secondptr = nullptr;
ListNode* thirdptr = new ListNode();
cout << thirdptr->value << '\n' << thirdptr->next << endl;
ListNode* fourptr = new ListNode(12, thirdptr);
cout << fourptr->value << '\n' << fourptr->next->value << endl;//测试构造函数是否起作用
delete fourptr; fourptr = nullptr; delete thirdptr; thirdptr = nullptr;
cout << "************************实用编码开始***************" << endl;
ListNode* numberList = nullptr;
// cinlist(numberList);//可以选择手动输入链表值,注意读入-1后就不继续读了。
printflist(numberList);//打印链表
deletelist(numberList);//delete链表
string numberFile = "numberfile.txt";//文本读取
string tt = "tt.txt";
cinlisttxt(numberList,numberFile,tt);
cout << "The contents of the list are: " << endl;
printflist(numberList);//打印
deletelist(numberList);//delete
}
二.txt文本
输入文本:
输出文本:
程序输出
总结
多多实践,链表结构广泛应用,包括二叉树,图的存储,有必要理解每一步的操作内容。