使用递归打印链接列表元素

时间:2016-11-16 17:53:15

标签: c++ recursion data-structures linked-list

我正在解决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
5
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

注意:节点的结构如下所示      struct Node       {          int数据;          struct Node * next;       }

3 个答案:

答案 0 :(得分: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';
}

答案 1 :(得分: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;
}

答案 2 :(得分:0)

您可以递归地反向链接列表,然后打印链接列表。

Node* reverse(Node* node) 
{ 
    if (node == NULL) 
        return NULL; 
    if (node->next == NULL)
    { 
        head = node; 
        return node; 
    } 
    Node* temp= reverse(node->next); 
    temp->next = node; 
    node->next = NULL; 
    return node;
}