C++中反向打印链表

Reverse print linked list in C++

我想实现链表。我写了一个插入列表方法,打印方法但是反向打印有问题。主要问题是反向打印打印的是正常列表,而不是反向打印:

#include <iostream>

struct Node
{
    int value;
    struct Node *next;
};

struct List
{
    struct Node *first, *last;
};

Node* node(int v)
{
    Node *newNode = new Node();
    newNode->value = v;
    newNode->next = NULL;
    return newNode;
}

List*  list()
{
    List *newList = new List();
    newList->first = NULL;
    newList->last = NULL;
    return newList;
}

List*  insert(List* s, Node* n)
{
    if (s->last == NULL)
    {
        n->next = s->last;
        s->last = n;
        s->first = n;
        return s;
    }

    s->last->next = n;
    s->last = s->last->next;
    return s;
}

void  print(List* s)
{
    Node *tmp = s->first;
    while(tmp)
    {
        std::cout << tmp->value << ' ';
        tmp = tmp->next;
    }
    std::cout << '\n';
}

void reverse_print(List* s)
{
    if(s->first == NULL)
    {
        std::cout << '\n';
        return;
    }

    else
    {
        std::cout << s->first->value << ' ';
        s->first = s->first->next;
        reverse_print(s);
    }
}

int main(int argc, char *argv[])
{
    List *myList2;
    myList2 = list();

    myList2 = insert(myList2, node(3));
    myList2 = insert(myList2, node(5));
    myList2 = insert(myList2, node(7));
    myList2 = insert(myList2, node(9));
    myList2 = insert(myList2, node(5));
    myList2 = insert(myList2, node(34));
    myList2 = insert(myList2, node(67));

    print(myList2);

    reverse_print(myList2);
}

改变

else
    {
        std::cout << s->first->value << ' ';
        s->first = s->first->next;
        reverse_print(s);
    }

else
    {
        reverse_print(s);
        s->first = s->first->next;
        std::cout << s->first->value << ' ';   
    }

应该可以帮助您有效地使用递归。

  1. 您不应修改正在打印的列表。
  2. 你应该先递归打印"the rest of the list"。

最好的方法是有一个单独的函数来打印节点:

void reverse_print(Node* n)
{
    if (n != NULL)
    {
        reverse_print(n->next);
        std::cout << n->value << ' ';
    }
}

void reverse_print(List* s)
{
    reverse_print(s->first);
}