In c++ write a program that will read lines from a text file put each line in a
ID: 3887695 • Letter: I
Question
In c++ write a program that will read lines from a text file put each line in a doubly linked list in reverse order then then put those lists in a main doubly linked list and reverse that one too.
ex file:
abc 123
efg 123
Expected results:
Reversed DLL:
NULL <-123<->abc<->NULL
NULL<-123<->efg<->NULL
Reversed main Doubly linked list of doubly linked lists:
NULL<- [NULL<-123<->efg<->NULL]->NULL
NULL<- [NULL <-123<->abc<->NULL]->NULL
DO NOT USE #include<list>!!
Explanation / Answer
//c++ code
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<fstream>
using namespace std;
struct node
{
string info;
struct node *next;
struct node *prev;
}*start;
class DoublyLinkedList
{
public:
DoublyLinkedList()
{
start = NULL;
}
void makelist(string);
void display();
void reverse();
};
int main()
{
ifstream in;
in.open("input.txt");
if(in==NULL)
{
cout<<"File opening error";
return 0;
}
string str;
int line=0;
while(getline(in,str))
{
DoublyLinkedList links;
int i=0,j=0,k=0;
char s[100][100];
while(str[i]!='')
{
if((int)str[i]==32)
{
s[j][k]='';
j++;
k=0;
}
else
{
s[j][k++]=str[i];
}
i++;
}
s[j][k]='';
for(i=j;i>=0;i--)
{
links.makelist(s[i]);
}
cout<<"Expected result"<<endl;
links.display();
links.reverse();
cout<<"Reversed List:"<<endl;
links.display();
cout<<" ";
}
}
void DoublyLinkedList::makelist(string data)
{
struct node *s, *temp;
temp = new(struct node);
temp->info = data;
temp->next = NULL;
if (start == NULL)
{
temp->prev = NULL;
start = temp;
}
else
{
s = start;
while (s->next != NULL)
s = s->next;
s->next = temp;
temp->prev = s;
}
}
void DoublyLinkedList::reverse()
{
struct node *p1, *p2;
p1 = start;
p2 = p1->next;
p1->next = NULL;
p1->prev = p2;
while (p2 != NULL)
{
p2->prev = p2->next;
p2->next = p1;
p1 = p2;
p2 = p2->prev;
}
start = p1;
}
void DoublyLinkedList::display()
{
struct node *q;
cout<<"NULL<->";
if (start == NULL)
{
cout<<"List empty"<<endl;
return;
}
q = start;
while (q != NULL)
{
cout<<q->info<<" <-> ";
q = q->next;
}
cout<<"NULL"<<endl;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.