如何使用类链表进行递归打印

How can I do a recursive print using class linked list

本文关键字:递归 打印 链表 何使用      更新时间:2023-10-16
//PROTOYPE
void Display();
//CALL
list.Display();
/***********************************
*  Print the contents of the list  *
***********************************/
void EmployeeList::Display()
{
    // Temporary pointer
    newEmployee * tmp;
    tmp = head;
    // No employees in the list
    if(tmp == NULL ) 
    {
        cout << "nntt***THERE IS NO EMPLOYEE INFORMATION STORED YET***n";
        return;
    }
    cout << "nn"
         << "tt************************************************n"
         << "tt*    Employee IDs and Yearly Salary DataBase   *n"
         << "tt************************************************nn";
    cout << "tttEmployee IDs" << setw(20) << right << "Yearly Salariesn";
    // One employee in the list
    if(tmp->Next() == NULL ) 
    {
        cout << "ttt    " << tmp->empID() << setw(13) << right << "  " 
             << "$" << setw(2) << tmp->ySalary() << endl;
    }
    else 
    {       
        do 
        {
            cout << "ttt    " << tmp->empID() << setw(13) << "  " 
                 << right << "$" << setw(2) << tmp->ySalary() << endl;
            tmp = tmp->Next();
        }while(tmp != NULL );
        cout << "nttt     ***Thank You***" << endl;
    }
}

我需要关于编写什么的帮助,以便对显示函数进行递归函数调用。我需要以从最后一个到第一个的相反顺序显示列表。如何使用类链表进行递归打印?

我将假设您的列表节点没有Previous()方法(否则,不使用递归实现反向打印循环将变得微不足道)。

尝试这样的事情:

void DisplayEmployeeInReverseOrder(newEmployee * emp)
{
    if (emp->Next() != NULL)
        DisplayEmployeeInReverseOrder(emp->Next());
    cout << "ttt    " << emp->empID() << setw(13) << right << "  " 
             << "$" << setw(2) << emp->ySalary() << endl;
}
void EmployeeList::Display()
{
    // Temporary pointer
    newEmployee * tmp;
    tmp = head;
    // No employees in the list
    if(tmp == NULL ) 
    {
        cout << "nntt***THERE IS NO EMPLOYEE INFORMATION STORED YET***n";
        return;
    }
    cout << "nn"
         << "tt************************************************n"
         << "tt*    Employee IDs and Yearly Salary DataBase   *n"
         << "tt************************************************nn";
    cout << "tttEmployee IDs" << setw(20) << right << "Yearly Salariesn";
    DisplayEmployeeInReverseOrder(tmp);
    cout << "nttt     ***Thank You***" << endl;
}