I post inputs at the bottom. Directions: Complete the following prelab assignmen
ID: 3852716 • Letter: I
Question
I post inputs at the bottom.
Directions:
Complete the following prelab assignment using the description given in each section. Be sure to comment your program; otherwise you may lose up to 5 points. You must use proper indent styles; otherwise you may lose up to 5 points. The input file is located on Blackboard under “input4.txt”.
Description:
typedef struct node_ {
int data;
struct node_* next;
}node;
void print_list(node* list);
Parameters:
list: A pointer to the head of a single linked list
Return: none
See example output, prints out the linked list
void free_list(node* list);
Parameters
list: A pointer to a single linked list
Return: None
This function should free each node in the linked list
node* create_list(char* file);
Parameters:
file: The name of the input file
Return: The head of the linked list
This function will open the input file and will build a linked list by malloc()ing a node for each of the numbers and linking them together.
int main(int argc, char* argv[]);
Main will read in an input file as a command line argument and then create a linked list, print it out and then free it.
Sample output:
./a.out input4.txt
1050->2050->2270->3050->3280->3330->3380->4050->4320->4520->4850->4970->4980->NULL
inputs:
1050
2050
2270
3050
3280
3330
3380
4050
4320
4520
4850
4970
4980
Explanation / Answer
#include<iostream.h>
#include<conio.h>
#include<malloc.h>
#include<fstream.h>
struct node_{
int data;
struct node_* next;
}*node;
void print_list(node_* list);
void free_list(node_* list);
node_* create_list(char* file);
void main(int argc, char* argv[]){
node=NULL;
node = create_list(argv[1]); //calling create list function.
print_list(node);//calling print_list function
free_list(node);//calling free_list function
}
node_* create_list(char* file){
ifstream fin; //creating ifstream object
fin.open(file);//opening file
int data;
while(fin>>data){
node_* ne;
ne=(node_*)(malloc(sizeof(node)));//allocating a new memory space
if(node==NULL){
ne->data=data;
ne->next=NULL;
node=ne;
}
else{
node_* temp;
for(temp=node;temp->next!=NULL;temp=temp->next);//traversing the list to find the last node
ne->data=data;
ne->next=NULL;
temp->next=ne;
}
}
return node;
}
void print_list(node_* list){
node_ *temp;
for(temp=list;temp!=NULL;temp=temp->next){
cout<<temp->data<<"->";
}
cout<<"NUll";
}
void free_list(node_* list){
list=NULL;//making the list to point to null will free the list from its content.
}