【问题标题】:print Linked List elements using recursion使用递归打印链接列表元素
【发布时间】:2017-03-31 01:20:26
【问题描述】:

我正在解决 Hackerrank 上的Print in reverse challenge

void ReversePrint(Node* head) 方法接受一个参数——链表的头部。你不应该阅读 来自标准输入/控制台的任何输入。头部可能是空的,因此不应打印任何内容。以相反的顺序打印链表的元素 标准输出/控制台(使用 printf 或 cout),每行一个。

示例输入

1 --> 2 --> 空

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

注意:节点的结构如下所示 结构节点 { 整数数据; 结构节点*下一个; }

【问题讨论】:

  • 在递归版本的结果中,我注意到在打印第二个输入集后重复了第一个输入集。为每个输入集打印后是否清除了全局向量的内容?
  • 抛弃全局向量。调用堆栈是递归方法的数据结构。
  • 请不要在此处询问有关在线代码判断引擎的问题。任何人都不太可能从他们的测试用例中告诉你你失败的地方,因为这些通常不会被披露。即使您测试的是在本地环境中运行,您也可能错过了测试在线挑战中应用的一些边缘案例。要有创意并尝试找到它们。此外,从长远来看,这些问题可能没有任何价值,除了在在线比赛中作弊,什么都学不到。
  • 我在运行第二个实现时评论了第一个实现。会不会影响结果
  • 没有。注释的代码不会被编译。

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


【解决方案1】:

为什么这么复杂?

/* 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';
}

【讨论】:

    【解决方案2】:

    如果你想返回反向链表:

      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;
    }
    

    【讨论】:

      【解决方案3】:

      您可以递归地反转链表,然后打印链表。

      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;
      } 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-06
        • 2013-12-12
        • 1970-01-01
        • 2016-05-07
        • 2021-11-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多