将数组实现转换为链接列表ADT

时间:2017-02-15 03:53:17

标签: c++ arrays linked-list type-conversion 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 average


    public:
        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

它将对此数据进行排序,并将此数据发送到一个如下所示的outfile:

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 个答案:

没有答案