(C++) Write a program that reads a list of words from the Words.txt file (shown
ID: 3877663 • Letter: #
Question
(C++) Write a program that reads a list of words from the Words.txt file (shown below), and stores it into a singly linked list, and prints the words from the singly linked list to the console in reverse order. Implement the program, as outlined below in the pseudocode, using singly linked list interface to store the data read from Words.txt. Demonstrate that the list of words does print in reverse using the 'prev' node (rather than the 'next' node). Include screenshot of output.
(Words.txt) is as follows, this code should work even if file is changed to many more words:
when
what
there
been
one
could
very
an
who
them
weekend
we
now
more
out
do
are
up
Explanation / Answer
here is your program : ----------------------->>>>>>>>>>>>>>>>
#include<iostream>
#include<fstream>
using namespace std;
template<class T>
class Node{
public:
T data;
Node *next;
};
template<class T>
class List{
Node<T> *head;
int count;
public:
List(){
head = NULL;
count = 0;
}
bool isEmpty(){
if(count == 0 && head == NULL){
return true;
}
return false;
}
~List(){
delete[] head;
}
bool add(T entry){
Node<T> *temp = new Node<T>;
temp->data = entry;
temp->next = NULL;
if(head == NULL){
head = temp;
count++;
return true;
}
temp->next = head;
head = temp;
count++;
return true;
}
bool remove(T entry){
if(isEmpty()){
cout<<" List is Empty";
return false;
}
Node<T> *temp = head;
Node<T> *prev = NULL;
while(temp != NULL){
if(temp->data == entry){
if(prev == NULL){
head = temp->next;
count--;
delete temp;
return true;
}
prev->next = temp->next;
count--;
delete temp;
return true;
}
prev = temp;
temp = temp->next;
}
}
void clear(){
if(isEmpty()){
}else{
delete[] head;
head = NULL;
count = 0;
}
}
int getFrequencyOf(T entry){
if(isEmpty()){
return 0;
}else{
Node<T> *temp = head;
int c = 0;
while(temp != NULL){
if(temp->data == entry){
c++;
}
temp = temp->next;
}
return c;
}
}
bool contains(T entry){
if(isEmpty()){
return false;
}else{
Node<T> *temp = head;
while(temp != NULL){
if(temp->data == entry){
return true;
}
temp = temp->next;
}
return false;
}
}
int length(){
return count;
}
void printReverse(){
if(isEmpty()){
cout<<" Lst is Empty : ";
}else{
Node<T> *temp = head;
while(temp != NULL){
cout<<temp->data<<" ";
temp = temp->next;
}
}
}
};
int main(){
List<string> words;
ifstream file;
char *f;
string word;
cout<<" Enter the file name of words : ";
cin>>f;
file.open(f);
if(file.is_open()){
while(!file.eof()){
file>>word;
words.add(word);
}
}else{
cout<<" File opening error : ";
exit(1);
}
words.printReverse();
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.