Question Write a C program The attached file is a small list
Question: Write a C++ program:-
The attached file is a small list of integers. Read the integers into a dynamically allocated linked structure of the following design:
struct IntList
{
IntList *next;
int value;
};
IntList *head;
List the integers as you read them in. Use the new operator to allocate an instance of IntList for each integer read. Let the variable head store the most recently return pointer from new. When creating a new structure instance, save the current value of head in the next member of the new IntList structure, then update head with the next pointer from new. After all the integers have been read, list them again in reverse order by starting at head and following the links stored in the next member. For the second part of the assignment, do the exact same thing using the vector type from the standard library definition <vector>.
I pasted the numbers below from the 4th largest.txt file.
Thank you so much for helping....
Solution
#include <iostream>
#include <fstream>
#include<vector>
std::ifstream infile(\"Largest.txt\");
using namespace std;
struct IntList
{
IntList *next;
int value;
};
IntList* newNode(int value)
{
IntList *temp = new IntList();
temp->value = value;
temp->next = NULL;
return temp;
}
IntList* addToList(IntList *head,int value)
{
if(head==NULL)
return newNode(value);
IntList *newNode_ = newNode(value);
newNode_->next = head;
return newNode_;
}
void printList(IntList *head)
{
IntList *temp = head;
if(head == NULL)
return;
printList(head->next);
cout << head->value << endl;
}
int main()
{
int temp;
IntList *head = NULL;
vector<int> items;
while(infile>>temp)
{
head = addToList(head,temp);
items.push_back(temp);
}
cout << \"Content of list is : \" << endl;
printList(head);
cout << \"Content of vector is : \" << endl;
for(int i=0;i<items.size();i++)
cout << items[i] << endl;
return 0;
}
OUTPUT:
Content of list is :
1233
1144
1288
2133
1944
1988
2744
1044
2688
3388
4833
1644
4088
5733
5144
1944
4788
6633
5944
2244
5488
7533
6744
2544
8433
7544
2844
Content of vector is :
1233
1144
1288
2133
1944
1988
2744
1044
2688
3388
4833
1644
4088
5733
5144
1944
4788
6633
5944
2244
5488
7533
6744
2544
8433
7544
2844
Process returned 0 (0x0) execution time : 0.022 s
Press ENTER to continue.



