文件读写和链表插入删除显示 5.17

来源:互联网 发布:mac windows截屏 编辑:程序博客网 时间:2024/04/28 15:24

#include<fstream>
#include<iostream>
#include<string>


using namespace std;


void CopyFile(string file1, string file2) //拷贝文档
{
ifstream fin(file1);//打开目标文件
ofstream fout(file2);//打开要写入的文件
string line;
while (!fin.eof())//文件没有结束时
{
getline(fin, line);//每次读一行
// cout << line << endl;
fout << line << endl;//输出到要写到的文档中
}
}


void ShowFile(string file) //显示文档的内容
{
ifstream fin(file);//打开目标文件
string line;
while (!fin.eof())
{
getline(fin, line);//每次读出一行内容
cout << line << endl;//然后在输出


}
}


void Reverse(string &s,int left,int right) //字符串逆序
{
if (left<=right)
{
char c = s[left];//开两个指针,将字符串头尾进行互相转换
s[left] = s[right];
s[right] = c;
Reverse(s, left + 1, right - 1);//递归方法实现
}


}


void Reverse2(string &s) //字符串逆序的非递归方式
{
int right = s.length()-1;
int left = 0;
while (left <= right)//通过使用WHILE语句避免了使用递归
{
char c = s[left];//里面原理与上面递归实现是一样的
s[left] = s[right];
s[right] = c;
left++;
right--;


}
}


class SNode
{
public:
SNode * next;
void Setdata(int data){ this->data = data; }
int Getdata(){ return data; }
SNode(){ next = NULL; data = -1; }
private:
int data;
};


class SList
{
public:
SNode *head;
void Insert(int data);
void DeleteNode(int data);
void Show();
SList();
};


SList::SList()
{
head = new SNode;
head->Setdata(-1);
head->next=NULL;
}


void SList::Insert(int data)
{
SNode *snode=new SNode;
snode->Setdata(data);
SNode *sn = head;
while (sn->next != NULL)
sn = sn->next;
sn->next = snode;
}


void SList::DeleteNode(int data)
{
SNode *sn = head;
while (sn->next != NULL)
{

if (sn->next->Getdata() == data)
{
if (sn->next->next == NULL)
{
delete sn->next;
}
else
{
SNode * s = sn->next;
sn->next = sn->next->next;
delete s;
}
break;
}
sn = sn->next;
if (sn->next == NULL)
cout << "not found" << endl;
}

}


void SList::Show()
{
SNode *sn = head->next;
while (sn!= NULL)
{
cout << sn->Getdata() ;
sn = sn->next;
}
cout << endl;
}


int main()
{
/*
string file1 = "a.txt";
string file2 = "b.txt";
ShowFile(file1);
ShowFile(file2);


CopyFile(file1, file2);
ShowFile(file2);*/


/*
string s = "abcdefghijklmnopqrstuvwxyz";
cout << s << endl;
// Reverse(s, 0, s.length()-1);
Reverse2(s);
cout << s << endl;*/


SList sl;


for (int i = 0; i < 10; i++)
{
sl.Insert(i);
sl.Show();
}


for (int i = 0; i < 10; i++)
{
sl.Show();
sl.DeleteNode(i);

}
return 0;
}
0 0
原创粉丝点击