#include <stdio.h>
//链节
struct Node{
int Data;
Node *next;
};
//链表类
class List{
Node *head=NULL;
public:
//在节点a前插入节点b
void Insert(int aData,int bData);
//删除指定节点
void Delete(int aData);
//清空节点
void Clear();
//返回链表链节数
int Length();
//返回该链表所有连接的next指针,类型为数组
void GetAll(int* allNode);
//从文件中加载链表数据
void LoadFromFile(char filepath[]);
//将链表保存到文件
void SaveToFile(char filepath[]);
//获取链头
Node* GetHead(){return head;}
};
void List::Insert(int aData,int bData){
Node *p,*q,*s;
s=(Node*) new (Node);//动态分配一个节点
s->Data=bData;//设b为此节点
p=head;
if (head==NULL){
//若是空表,使b作为第一个节点
head=s;
s->next=NULL;
}
else{
if (p->Data==aData){
//若a为第一个节点
s->next=p;
head=s;
}
else{
//查找节点a
while (p->Data != aData && p->next != NULL){
q=p;
p=p->next;
}
if (p->Data == aData){
//若有节点a
q->next=s;
s->next=p;
printf("\n%d\n",aData);
}
else{
//若没有节点a,将b节点添加到末尾
p->next=s;
s->next=NULL;
}
}
}
}
void List::Delete(int aData){
Node *p,*q;
p=head;
if (p==NULL){
//若是空表
return ;
}
if (p->Data==aData){
//若a为第一个节点
head=p->next;
delete p;
}
else{
while (p->Data!=aData && p->next !=NULL){
//查找节点a
q=p;
p=p->next;
}
if (p->Data ==aData){
//若有节点a
q->next =p->next;
delete p;
}
}
}
void List::Clear(){
Node *p,*current;
current = head->next;
p=head;
delete p;
while (current != NULL){
current=p->next;
p=current;
delete p;
}
head=NULL;
}
int List::Length(){
int ListLengh=0;
Node *current = head;
while (current != NULL){
current=current->next;
ListLengh+=1;
}
return ListLengh;
}
void List::GetAll(int* allNode){
Node* current = head;
current=head;
//获取所有链接的next指针
int count=0;
while (current != NULL){
*(allNode+count) = current->Data;
current=current->next;
count +=1;
}
}
void List::LoadFromFile(char filepath[]){
int data;
FILE *fp;
fp=fopen(filepath,"r");
List::Clear();
while (fscanf(fp,"%d\n",&data)){
List::Insert(-1,data);
}
}
void List::SaveToFile(char filepath[]){
FILE *fp;
fp=fopen(filepath,"w+");
Node *current = head;
while (current != NULL){
fprintf(fp,"%d\n",current->Data);
current=current->next;
}
fclose(fp);
}
int main(){
List A;
//插入数据
A.Insert(0,10);
A.Insert(0,20);
A.Insert(0,30);
//输出数据长度
printf("%d\n",A.Length());
printf("==========分割线=============\n");
//获取全部数据
int a[A.Length()];
A.GetAll(a);
int i;
for (i=0;i<3;i++){
printf("%d\n",*(a+i));
}
printf("==========分割线=============\n");
//删除data=10的数据
A.Delete(10);
//获取全部数据
int b[A.Length()];
A.GetAll(b);
for (i=0;i<2;i++){
printf("%d\n",*(b+i));
}
printf("==========分割线=============\n");
//保存数据
A.SaveToFile("lianbiao.txt");
//再插入一条数据
A.Insert(-1,40);
//打印
int c[A.Length()];
A.GetAll(c);
for (i=0;i<3;i++){
printf("%d\n",*(c+i));
}
printf("==========分割线=============\n");
//从文件中加载数据
A.LoadFromFile("lianbiao.txt");
//打印
int d[A.Length()];
A.GetAll(d);
for (i=0;i<A.Length();i++){
printf("%d\n",*(c+i));
}
printf("==========分割线=============\n");
return 0;
}
网友评论