C++ 递归反向列表

C++ 递归反向列表,c++,pseudocode,C++,Pseudocode,我需要编写一个名为reverseNodes的算法,该算法将RefToNode作为参数,并recuriveley反转我得到的标题所对应的列表 反向算法(rList) 回响列表中的元素 Pre:rList::对要反转的列表的引用 Post:rList中的元素被反转 如果(rList!=NULL) 反向节点(rList->head) 返回 我需要找到一种写这是伪代码的方法,并找到时间复杂性有时候,如果你开始的话,创建一些非形式化的算法会更容易 这个想法表达得很清楚。然后,模糊和口头表达,直到你有什么,

我需要编写一个名为reverseNodes的算法,该算法将RefToNode作为参数,并recuriveley反转我得到的标题所对应的列表

反向算法(rList)

回响列表中的元素

Pre:rList::对要反转的列表的引用

Post:rList中的元素被反转

如果(rList!=NULL) 反向节点(rList->head) 返回


我需要找到一种写这是伪代码的方法,并找到时间复杂性

有时候,如果你开始的话,创建一些非形式化的算法会更容易 这个想法表达得很清楚。然后,模糊和口头表达,直到你有什么,你的教授会高兴地接受

那么,让我们从算法的总体思路开始:

let rec fold folder acc l = 
    match l with
    | [] -> acc
    | x::xs -> fold folder (folder acc x) xs

let prepend l e = e :: l

let revlist l = fold prepend [] l
…然后开始说:

  • 让结果=空列表
  • 让l=我们要反转的列表
  • 如果l是空列表,转到7
  • 让头部=左前,左=左前
  • 结果:推动前盖
  • 转到3
  • l=结果
  • 步骤3..6可以很容易地表示为递归函数:

    void loop(list& l, list& result)
    {
        if( l.is_empty()) return;
        auto head = l.front();
        l.pop_front();
        result.push_front(head);
        loop(l,result);
    }
    
    当我们想要创建in-place.reversion的幻觉时,我们的reverse_list函数是

    void reverse_list( list& l )
    {
        list result;
        loop( l, result);
        l = result;
    }
    
    替代解决方案

    我们也可以用另一种方式:

    let rec revlist1 l =
        match l with
        | [] -> l
        | x::xs -> (revlist1 xs) @ [x]
    
    这基本上说明,反转列表是原始列表的前面元素,附加到其余列表的背面

    将算法转换为乱七八糟的形式会产生:

    Node* reverse_list1( Node* list )
    {
        if( list == NULL) return NULL; // reverse of empty list is empty list.
        if( list->next == NULL ) // last element in list?
            return list; // the reverse of a list with 1 element is the same.
        else
        {
            Node* head = list;
            Node* tail = list->next;
            head->next = NULL;
            Node* end_of_reverse_tail = tail; // the first will be the last...
            Node * result = reverse_list1(tail);
            end_of_reverse_tail->next = head;
            return result;
        }
    }
    

    请注意,这不是尾部递归解决方案

    如果我聪明的话,我会在互联网上搜索“c++反向链表示例”。但是,我想今天不是聪明的一天。很好地解释了@BitTickler!我对函数式语言的这种明显宣传投了更高的票,不知道这些链接能维持多久,但是。。。。显示正在运行的替代解决方案。