1. 程式人生 > >單鏈表各種操作(逆向列印以及逆轉)的c++實現

單鏈表各種操作(逆向列印以及逆轉)的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();
}