我正在创建一个小程序,从txt文件填充链接列表,然后我想在链接列表上进行一些操作,然后再将其保存回文件。
但是,我对如何访问我创建的链表的节点感到有些困惑 - 以及我如何遍历列表并仅打印某些节点(例如仅限姓名)。 / p>
关联列表结构
struct EmployeeLL
{
string position;
string firstName;
string lastName;
string startDate;
float empNumber;
string deptartment;
float salary;
float hourlyRate;
float hoursPerWeek;
EmployeeLL *link;
};
加载链接列表:
void loadLinkedList()
{
fstream in("payroll.txt", ios::in);
string position, first, last, date, dept;
float salary, rate, week, emp;
EmployPtr head = new EmployeeLL;
while (in >> position >> first >> last >> date >> emp >> dept >> salary >> rate >> week)
{
cout << position << ", " << first << ", " << last << ", " << date << ", " << emp << ", " << dept << ", " << salary << ", " << rate << ", " << week << endl;
insertAtHead(head, position, first, last, date, emp, dept, salary, rate, week);
}
in.close();
}
将读取值插入链接列表
void insertAtHead(EmployPtr& head, string positionValue, string firstNameValue, string lastNameValue, string startDateValue, float empValue, string deptValue,
float salaryValue, float hourlyRateValue, float hoursPerWeekValue)
{
EmployPtr tempPtr = new EmployeeLL;
tempPtr->position = positionValue;
tempPtr->firstName = firstNameValue;
tempPtr->lastName = lastNameValue;
tempPtr->startDate = startDateValue;
tempPtr->empNumber = empValue;
tempPtr->deptartment = deptValue;
tempPtr->salary = salaryValue;
tempPtr->hourlyRate = hourlyRateValue;
tempPtr->hoursPerWeek = hoursPerWeekValue;
tempPtr->link = head;
head = tempPtr;
}
这是我感到困惑的地方。我想知道如何打印(例如)链表中每个人的名字和姓氏?
这是我到目前为止尝试的代码:
void printNames(EmployPtr& head)
{
EmployeeLL* thisNode = head;
if (head == NULL)
{
cout << "The list is empty\n";
return;
}
else
cout << "---------------------------------------------------------\n";
cout << "\tFirstName\tLastName\n";
cout << "---------------------------------------------------------\n";
do
{
cout << setw(8) << left << thisNode->firstName;
cout << setw(16) << left << thisNode->lastName;
cout << "\n\t";
} while (thisNode != NULL);
{
cout << "\n\n";
}
}
答案 0 :(得分:2)
有三个问题。 loadLinkedList
函数中的第一个:
您不应创建初始化EmployeeLL
指向的初始head
节点。您应该将head
初始化为空指针:
EmployPtr head = nullptr;
您不会返回您从该函数创建的列表。一旦loadLinkedList
返回,列表将永远丢失。
在printNames
函数的循环中,您永远不会更改thisNode
点的位置。你永远不会遍历列表,而是一遍又一遍地打印列表中的第一个节点。
答案 1 :(得分:1)
您缺少移动到下一个节点。
...
thiNode = thisNode->link; //move to the next node
} while (thisNode != NULL);