首页 文章

使用递归打印Linked List元素

提问于
浏览
0

我在Hackerrank上解决了Print in reverse challenge

void ReversePrint(Node * head)方法采用一个参数 - 链表的头部 . 你不应该从stdin / console读取任何输入 . 头部可能是空的,因此不应打印任何东西 . 以相反的顺序将链接列表的元素打印到stdout / console(使用printf或cout),每行一个 . 样本输入1 - > 2 - > NULL 2 - > 1 - > 4 - > 5 - > NULL样本输出2
1

4
1
2

我用它解决了这个问题

#include <vector>
    void ReversePrint(Node *head)
{
  // This is a "method-only" submission. 
  // You only need to complete this method. 

    std::vector<int> nodeList;
    if(head != NULL){

        while(head != NULL){
            nodeList.push_back(head->data);
            head = head->next;            
        }

        for (std::vector<int>::iterator it = nodeList.end()-1 ; it != nodeList.begin()-1; --it){
            std::cout << *it <<endl;
       }
    }

}

它工作得很好,但扩展到使用递归提供了错误的答案,为什么会发生这种情况?

std::vector<int> nodeList;
void ReversePrint(Node *head){
    if(head != NULL){
        nodeList.push_back(head->data);
        ReversePrint(head->next);
    }
    else{
        for (std::vector<int>::iterator it = nodeList.end()-1 ; it != nodeList.begin()-1; --it){
            std::cout << *it <<endl;
       }

    }

}

结果是

2
1
5
4
1
2
2
1

注意:Node的结构以struct Node {int data; struct Node * next; }

2 回答

  • 6

    为什么这么复杂?

    /* Function to reverse print the linked list */
    void ReversePrint(Node* head)
    {
        // Base case  
        if (head == NULL)
           return;
    
        // print the list after head node
        ReversePrint(head->next);
    
        // After everything else is printed, print head
        std::cout << head->data << '\n';
    }
    
  • 0

    如果您想要返回反向链表:

    Node* List::reverseList()
    {
        if(head == NULL) return;
    
        Node *prev = NULL, *current = NULL, *next = NULL;
        current = head;
        while(current != NULL){
            next = current->next;
            current->next = prev;
            prev = current;
            current = next;
        }
        return prev;
    }
    

相关问题