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

时间:2016-03-08 02:39:03

标签: c++ linked-list abstract-class

//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 << "\n\n\t\t***THERE IS NO EMPLOYEE INFORMATION STORED YET***\n";
        return;
    }

    cout << "\n\n"
         << "\t\t************************************************\n"
         << "\t\t*    Employee IDs and Yearly Salary DataBase   *\n"
         << "\t\t************************************************\n\n";

    cout << "\t\t\tEmployee IDs" << setw(20) << right << "Yearly Salaries\n";

    // One employee in the list
    if(tmp->Next() == NULL ) 
    {
        cout << "\t\t\t    " << tmp->empID() << setw(13) << right << "  " 
             << "$" << setw(2) << tmp->ySalary() << endl;
    }

    else 
    {       
        do 
        {
            cout << "\t\t\t    " << tmp->empID() << setw(13) << "  " 
                 << right << "$" << setw(2) << tmp->ySalary() << endl;

            tmp = tmp->Next();

        }while(tmp != NULL );

        cout << "\n\t\t\t     ***Thank You***" << endl;
    }
}

为了对Display函数执行递归函数调用,我需要有关写入内容的帮助。 我需要从上到后以相反的顺序显示列表。 如何使用类链表进行递归打印?

1 个答案:

答案 0 :(得分:0)

我将假设您的列表节点没有Previous()方法(否则反向打印循环在不使用递归的情况下实现起来很简单。)

尝试这样的事情:

void DisplayEmployeeInReverseOrder(newEmployee * emp)
{
    if (emp->Next() != NULL)
        DisplayEmployeeInReverseOrder(emp->Next());

    cout << "\t\t\t    " << 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 << "\n\n\t\t***THERE IS NO EMPLOYEE INFORMATION STORED YET***\n";
        return;
    }

    cout << "\n\n"
         << "\t\t************************************************\n"
         << "\t\t*    Employee IDs and Yearly Salary DataBase   *\n"
         << "\t\t************************************************\n\n";

    cout << "\t\t\tEmployee IDs" << setw(20) << right << "Yearly Salaries\n";

    DisplayEmployeeInReverseOrder(tmp);

    cout << "\n\t\t\t     ***Thank You***" << endl;
}