Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 3

#include <iostream>

#include <fstream>
#include <string>
using namespace std;
struct list {
string data;
list* next;
};
class f_handling
{
public:
list* head = new list;
list* tail;
f_handling()
{
head->next = nullptr;
tail = head;
}
void add_begin();
void add_end();
void display();
void delete_();
};
void f_handling :: add_begin()
{
list* newnode = new list;
newnode->next = nullptr;
cout << "Enter Data: " << endl;
cin >> newnode->data;
if (head->next != NULL)
{
newnode->next = head->next;
}
else
{
tail = newnode;
}
head->next = newnode;
fstream myfile;
myfile.open("data.txt");
fstream temp;
temp.open("temp.txt", std::ios_base::app);
string line;
temp << newnode->data << endl;
while (getline(myfile, line))
{
temp << line << endl;
}
myfile.close();
temp.close();
remove("data.txt");
rename("temp.txt", "data.txt");
}
void f_handling::add_end()
{
list* newnode = new list;
newnode->next = NULL;
cout << "Enter Data: " << endl;
cin >> newnode->data;
newnode->next = nullptr;
tail->next = newnode;
tail = newnode;
fstream myfile;
myfile.open("data.txt", std::ios_base::app);
myfile << newnode->data << endl;
}
void f_handling::display()
{
fstream myfile;
myfile.open("data.txt");
string line;
while (getline(myfile, line))
{
cout << line << endl;
}
}
void f_handling::delete_()
{
string s;
cout << "Enter value you want to delete: ";
cin >> s;
fstream myfile;
myfile.open("data.txt");
fstream temp;
temp.open("temp.txt", std::ios_base::app);
string line;
int flag = 0;
while (getline(myfile, line))
{
if (line == s)
{
flag = 1;
}
else
{
temp << line << endl;
}
}
if (flag == 0)
cout << "***NOT FOUND***" << endl;
myfile.close();
temp.close();
remove("data.txt");
rename("temp.txt", "data.txt");
}
int main()
{
f_handling s;
int x;
do {
cout << "1. Add Element at beginning" << endl;
cout << "2. Add Element at end" << endl;
cout << "3. Delete Element " << endl;
cout << "4.Display List" << endl;
cout << "5.Exit" << endl;
cin >> x;
switch (x)
{
case 1:
s.add_begin();
break;
case 2:
s.add_end();
break;
case 3:
s.delete_();
break;
case 4:
s.display();
break;
}
}
while (x != 5);
}

You might also like