Преобразование реализации массива в связанный список ADT

Что мне нужно сделать со следующим кодом, чтобы сделать его реализацией связанного списка вместо реализации массива?

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
//#include "Player.h"
using namespace std;

class Player
{
private:
string first;  // player's first name
string last;   // player's last name
string pos;   // player's primary position
double batave;  // batting averagepublic:
Player(); // Default Constructor

void Initialize(string, string, string, double); // copies data into the object with some simple formatting and data checking

void Read(istream&); // define methods to read and write simple versions of player data to/from

void Write(ostream&);

double getBattingAverage(); // define get/sets as needed

string getFirstName();
string getLastName();
string getFullName();
string getPosition();
};Player::Player() // Default constructor - set player to predefined values
{
// use the Initialize method since we have one
Initialize("unknown", "unknown", "tbd", 0.0);
}void Player::Initialize(string first, string last, string pos, double avg) // copies data into the object with some simple formatting and data checking
{
first = first;
last = last;
pos = pos;
if (avg < 0) avg = -avg;  // at least try to correct
batave = avg;
}

// define methods to read and write simple versions of player data
// to/from streams

// Read assumes the player's data is in the input stream in the format:
// firstname lastname position average with only spaces between the data
// no other separator characters are used.  This will not work if a player's
// name has embedded spaces!
void Player::Read(istream &input)
{
char temp[100];  // using a temporary buffer to read input from stream
input >> temp;
first = temp;
input >> temp;
last = temp;
input >> temp;
pos = temp;
input >> batave;

Player.Additem();
}// Write the Player data to an output stream with simple formatting
void Player::Write(ostream &out) {
out << last << ", " << first << ": " << pos;
out << fixed;
out << setprecision(3);
out << " (" << batave << ") ";
}

// define get/sets as needed
double Player::getBattingAverage() { return batave;  }
string Player::getFirstName() { return first; }
string Player::getLastName() {  return last; }
string Player::getFullName() {  return  first + " " + last; }
string Player::getPosition() { return pos; }int main (void)
{
const int FNLENGTH = 100;           // use a reasonable size for filenames
char      inputFileName[FNLENGTH];  // create buffers to store filenames
char      outputFileName[FNLENGTH];
ifstream  inFile;                   // create file objects for our 2 files
ofstream  outFile;

const int MAXPLAYERS = 50;
Player    playerList[MAXPLAYERS];   // array to store player objects
Player    currentPlayer;            // current player being retrieved from data file
int       playerCount;              // count players as they are retrieved
int       i;                        // loop counter

// Prompt the user and open the input data file
cout << "Please enter the name of your input data file: ";
cin >> inputFileName;

inFile.open(inputFileName);
if (inFile.fail()) {  // file open failed
cout << "\nError opening input file.  Cannot process player data. \nExiting Program.\n" << endl;
return 0;         // NOTE THIS IS THE ONLY TIME I ALLOW AN EMBEDDED RETURN or BREAK type exit IN A PROGRAM
}

// file opened successfully
playerCount = 0;
while (!inFile.eof() && playerCount < MAXPLAYERS) // as long as there are lines of data to be read in read in a player
{
currentPlayer.Read(inFile);

//playerList[playerCount] = currentPlayer;  // store in list
Player.Additem(currentPlayer);
playerCount++; // count the player
}

inFile.close();

// Now write the player data to the desired output file
cout << "Please enter the name of your output data file: ";
cin >> outputFileName;
outFile.open(outputFileName);  // as long as there is space on disk, this won't fail

outFile << "There were " << playerCount << " players in the input data file: \n" << endl;
for (i = 0;  i < playerCount; i++) {
playerList[i].Write(outFile);
outFile << endl;
}

outFile.close();

cout << "\n\nProgram 1 Complete.\nYour output is stored in the file named " << outputFileName << endl;
return 0;
}

Я до сих пор пытался создать функцию addplayer (), такую ​​как:

void Player::addplayer(string first, string last, string pos, double avg) // Stores the data in the linked list
{
first = first;
last = last;
pos = pos;
if (avg < 0) avg = -avg;  // at least try to correct
batave = avg;

if (head != NULL)
{
while (temp -> next != NULL)
{
temp = temp -> next;
}

temp -> next = new node;
count++;

temp = temp -> next;

temp -> item = first;

temp -> next = NULL;

}
else
{
head = new node;
count++;

// head -> DOW = day; code used from other project
// head -> spent = dollars;

head -> next = NULL;
temp = head;
}

}

Итак, в основном я пытаюсь реализовать первый фрагмент кода в виде связанного списка, и это то, что я до сих пор:

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;using namespace std;

struct node
{   string item;
node* next;
};

class Player
{
private:
node* head;
node* temp;
int count;

string first;    // player's first name
string last;     // player's last name
string pos;      // player's primary position
double batave;   // batting average

public:
Player(); // Constructor for the class

// Add player to list
void initialize(string first, string last, string pos, double avg);
void addplayer(string, string, string, double);
bool isempty(); // Test if empty

void print();~Player(); // Destructor de-allocates memory used by the list.
};
Player::Player()
{
head = NULL;
}

bool isempty()
{

}

void Player::addplayer(string first, string last, string pos, double avg) // Stores the data in the linked list
{
first = first;
last = last;
pos = pos;
if (avg < 0) avg = -avg;  // at least try to correct
batave = avg;

if (head != NULL)
{
while (temp -> next != NULL)
{
temp = temp -> next;
}

temp -> next = new node;
count++;

temp = temp -> next;

temp -> item = first;

temp -> next = NULL;

}
else
{
head = new node;
count++;

// head -> DOW = day; code used from other project
// head -> spent = dollars;

head -> next = NULL;
temp = head;
}

}

int main(void)
{
ifstream  infile; // create file objects for our 2 files
ofstream  outfile;
string filename, filename2;

cout << "Hello! Please enter a valid file name (e.g. stats.txt)" << endl;
cin >> filename;

infile.open(filename.c_str());

if(!infile)
{
cout << "We're sorry! The file specified is unavailable!" << endl;
}
else
{
cout << "The file has been opened!" << endl << endl << endl;

// call function
// call function}//\\//\\//\\//\\//\\//\\//\\
printf("\n\n\n");
system("pause");
}

Будем очень благодарны за любые советы и примеры кода, которые вы, ребята, можете предложить. Раньше мне никогда не приходилось «конвертировать» код … поэтому я пытаюсь начать все сначала, но начать все еще сложно для меня. Я просто хочу конвертировать из массива в связанный список, и это оказывается сложно.
Программа будет читать в файле статистики игрока:

Chipper Jones 3B 0.303
Rafael Furcal SS 0.281
Hank Aaron RF 0.305

где он будет сортировать эти данные и отправлять эти данные в выходной файл, который будет выглядеть так:

There were 3 players in the input data file:
Jones, Chipper: 3B (0.303)
Furcal, Rafael: SS (0.281)
Aaron, Hank: RF (0.305)

Это то, что оригинальная программа делает с реализацией массива. Я просто пытаюсь перейти от массива к связанному списку … Я хотел знать самый простой способ сделать это. Пожалуйста помоги.

0

Решение

Задача ещё не решена.

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector