#include<iostream>
#include<fstream>
#include<ctime>
using namespace std;
struct Node
{
int data;
struct Node* next;
};
typedef struct Node* PtrToNode;
typedef PtrToNode Position;
typedef PtrToNode List;
List createList()
{
List L = (PtrToNode)malloc(sizeof(struct Node));
if (L == NULL)
cout << "分配内存失败!" << endl;
else
L->next = NULL;
return L;
}
void addList(List L,int e)
{
PtrToNode tmpcell = (PtrToNode)malloc(sizeof(struct Node));
if (tmpcell == NULL)
cout << "分配内存失败!" << endl;
else
{
//头插法
tmpcell->data = e;
tmpcell->next = L->next;
L->next = tmpcell;
}
}
void printList(List L)
{
Position p = L->next;
while (p)
{
cout << p->data << " ";
p = p->next;
}
}
int main()
{
List L = createList();
srand(unsigned int(time(0)));
ofstream output;
output.open("data.txt");
for (int i = 0; i < 100; i++)
{
int tmp = rand() % 100;
output << tmp << " ";
}
output.close();
ifstream input;
input.open("data.txt");
int shuju;
input >> shuju;
while (!input.eof())
{
addList(L, shuju);
input >> shuju;
}
input.close();
printList(L);
return 0;
}
将数据存入txt文件中,从文件中读取数据到单链表当中,再打印单链表
最新推荐文章于 2022-06-18 15:43:29 发布