首页 > 解决方案 > C++链表非成员函数反向打印

问题描述

所以我了解了如何使用递归以相反的顺序打印单个链表。我在做非成员函数时遇到了麻烦。例如在int print_reverse(IntSLList & list))函数中如何以迭代方式打印反向?

************************  .h  file **************************
class IntSLLNode {
public:
    IntSLLNode() {
        next = 0;
    }
    IntSLLNode(int el, IntSLLNode *ptr = 0) {
        info = el; next = ptr;
    }
    int info;
    IntSLLNode *next;
};

class IntSLList {
public:
    IntSLList() {
        head = 0;
    }
    ~IntSLList();
    int isEmpty() {
        return head == 0;
    }
    void addToHead(int);
    void addToTail(int);
    int  deleteFromHead(); // delete the head and return its info;
    int  deleteFromTail(); // delete the tail and return its info;
    bool isInList(int) const;
    void printAll() const;
    
private:
    IntSLLNode *head;
};

这是主要的

************************ main **************************
#include <iostream>
using namespace std;

#include "intSLList.h"

int print_reverse(IntSLList & list){


  if (head == NULL)  
     return;  
  printReverse(head->next); 

  cout << head->data << " ";  

 //How to compelete this in an iterative(or recursive if iterative is too much work)way ?
 //like this?       
}


int main() {

    IntSLList list;
    
    list.print_reverse(list);

}

新增功能

标签: c++classlinked-listnon-member-functions

解决方案


标题实际上无法访问列表的内容,除非通过销毁它。所以……这就是我们要做的。

int  deleteFromTail(); // delete the tail and return its info;

除了我们需要进行额外的步骤并重建它,因为没有人期望打印容器会破坏其内容。见https://en.wikipedia.org/wiki/Principle_of_least_astonishment

#include <iostream>
#include <stack>
#include <list>

class IntSLList {
public:
    int isEmpty() { return m_list.empty(); }
    void addToHead(int i) { m_list.push_front(i); }
    void addToTail(int i) { m_list.push_back(i); }
    int  deleteFromHead() {
        int temp = m_list.front();
        m_list.pop_front();
        return temp;
    }
    int  deleteFromTail() { 
        int temp = m_list.back();
        m_list.pop_back();
        return temp;
    }

private:
    // no implementation given so I'm using std::list internally.
    std::list<int> m_list;
};

int print_reverse(IntSLList& mylist) {
    // store the data we are destroying in temp
    IntSLList temp;

    // literally the only way we can access the contents of the container is destructive so ... guess we're going there
    while (!mylist.isEmpty()) {
        int back = mylist.deleteFromTail();
        std::cout << back << std::endl;
        temp.addToHead(back);
    }

    // now rebuild the original list. I told you this would be bad.
    while (!temp.isEmpty()) {
        mylist.addToHead(temp.deleteFromTail());
    }

    // maybe this was supposed to be length, but not documented so I can return whatever I want.
    return -1;
}

int main() {
    IntSLList mylist;
    mylist.addToTail(1);
    mylist.addToTail(2);
    mylist.addToTail(3);
    print_reverse(mylist);
}

3
2
1


推荐阅读