且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 C++ 中以相反的顺序打印我的链表

更新时间:2023-11-10 10:37:40

printList中,还要检查head == NULL,否则就是访问成员指向 NULL 的指针.以下应该有效.

Within printList, you have to also check for head == NULL, otherwise you are acessing members of a pointer pointing to NULL. The following should work.

    void printList()
    {
        node *temp = head;
        while(temp != NULL) // don't access ->next
        {
            cout << temp->data << endl;
            temp = temp->next;
        }
    }

printReverse() 中,我真的不明白为什么每次迭代都要打印元素计数的一半并打印两个元素.但是,您在这里真的不需要 for 循环.您可以在循环结束后在 temp == head 后立即停止,因为那时您只是打印了头部.并且只打印一个元素,该元素的 next 指针指向之前打印的元素.

In printReverse() I really can't understand why you take half of the counts of the elements to print and print two elements in every iteration. However, you really don't need a for-loop here. You can simply stop as soon as temp == head after your loop, since then you just printed the head. And only print one element, the one whose next pointer points to the previously printed element.

另一个递归的尝试解决这个问题看起来像这样:

Another, recursive, attempt to solve the problem looks like this:

    void printReverse()
    {
        printReverseRecursive(head);
    }
    void printReverseRecursive(node *n)
    {
        if(n) {
            printReverseRecursive(n->next);
            cout << n->data << endl;
        }
    }