单链表各种操作(逆向打印以及逆转)的c++实现

#include <iostream>
using namespace std;
class Node;
class List{
public:
    List(void):m_head(NULL),m_tail(NULL){}
    ~List(void){
        for(Node* next;m_head;m_head = next){
            next = m_head->m_next;
            delete m_head;
        }
    }
    void append(int data){
        Node* node = new Node(data);
        if(m_tail){
            m_tail->m_next = node;
        }
        else
            m_head = node;
        m_tail = node;
    }
    size_t size(void)const{
        size_t cn = 0;
        for(Node* node = m_head;node;node = node->m_next)
            ++cn;
        return cn;
    }
    void print(void)const{
        for(Node* node= m_head;node;node = node->m_next)
            cout << node->m_data << " ";
        cout << endl;
    }
    void rprint(void)const{
        rprint(m_head);
        cout << endl;
    }
    void reverse(void){
        reverse(m_head);
        swap(m_head,m_tail);
    }
private:
    class Node{
    public:
        Node(int data = 0,Node* next = NULL):m_data(data),m_next(next){}
        int m_data;
        Node* m_next;
    };
    Node* m_head;
    Node* m_tail;
    void rprint(Node* node) const{
        if(node){
            rprint(node->m_next);//先打印以node->m_next为首的链表,在打印自己就是逆向打印了.
            cout << node->m_data << " ";
        }
    }
    void reverse(Node* node){
        if(node && node->m_next){//至少两个节点才需要逆转,注意必须判断node->m_next,否则程序会core
            reverse(node->m_next);
            node->m_next->m_next = node;
            node->m_next = NULL;
        }
    }
};
int main(void)
{
    List list;
    for(int i = 0;i < 10;++i)
        list.append(i);
    cout << list.size() << endl;
    list.print();
    list.rprint();
    list.reverse();
    list.print();
}

猜你喜欢

转载自blog.csdn.net/wWX336815/article/details/82427130