In: Computer Science
Given an array of Student type and size 10, create a linked list of students by linking students with an odd index first and then linking students with an even index. Write a loop to print out the students in the linked list
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
const int NUM = 10;
struct Student{
string fName;
string lName;
Student * next;
};
int main() {
Student stuArr[NUM];
ifstream myfile;
myfile.open("Test.txt");
for(int i = 0; i < NUM; i++)
{
myfile>>stuArr[i].fName;
myfile>>stuArr[i].lName;
stuArr[i].next = 0;
}
//cpp program for implementing linked list
#include<bits/stdc++.h>
using namespace std;
const int NUM = 10;
typedef struct Student{
string fName;
string lName;
struct Student *next;
}Student;
// declaring getnode funtion to create a Student type node to add to the linked list.
Student* gettingnode(){
Student* node = NULL;
node = new Student();;
node->fName;
node->lName;
node->next = NULL;
return node;
}
//main function is started from here
int main()
{
Student stuArr[NUM];
ifstream myfile;
myfile.open("C:/Users/Desktop/linkedtest.txt"); //location of text file
for(int i = 0; i < NUM; i++)
{
myfile>>stuArr[i].fName;
myfile>>stuArr[i].lName;
stuArr[i].next = 0;
}
Student *head = gettingnode();
// making index 1 of array element as the head of the linked list.
head->fName = stuArr[1].fName;
head->lName = stuArr[1].lName;
Student *temp = NULL;
Student *temp1 = head;
int idx = 3;
// looping on all the odd indexes first.
while(idx < 10){
temp = gettingnode();
temp->fName = stuArr[idx].fName;
temp->lName = stuArr[idx].lName;
temp1->next = temp;
temp1 = temp;
idx = idx + 2;
}
idx = 0;
// looping on all the even indexes finally.
while(idx < 10){
temp = gettingnode();
temp->fName = stuArr[idx].fName;
temp->lName = stuArr[idx].lName;
temp1->next = temp;
temp1 = temp;
idx = idx + 2;
}
Student *iter = head;
// printing the entire list.
while(iter){
cout<< iter->fName<<" "<<iter->lName<<endl;
iter = iter->next;
}
return 0;
}
Here is the output screen:
linkedtest.txt file