单链表(C++模板类)

list.h:

#ifndef LIST_CLA_H
#define LIST_CLA_H

template <typename T>
class List;

template <typename T>
class Node
{
public:
    friend class List;
    Node(T i);
private:
    T value;
    Node* next;
};
template <typename T>
class List
{
public:
    List();
    ~List();

    void clear();
    void append(T i);
    void insert(int position, T x);
    T at(int i);
    void removeAt(int i);
    void remove(T x);
    int size()const;
private:
    Node* header;
};

#include "list_def.h"

#endif // !LIST_H

list_def.h:

#include "list.h"
#ifndef LIST_DEF_H
#define LIST_DEF_H

templateT>
Node<T>::Node(T i)
    :value(i), next(nullptr)
{
}

templateT>
List<T>::List()
{
    header = new Node<T>(0);
}

templateT>
List<T>::~List()
{
    clear();
    delete header;
    header = nullptr;
}

templateT>
void List<T>::clear()
{
    Node<T>* p = header;
    while (p != nullptr && p->next != nullptr)
    {
        p = p->next;
        header->next = p->next;
        delete p;
        p = header;
    }
}

templateT>
void List<T>::append(T i)
{
    Node<T> *n = new Node<T>(i);
    Node<T> *p = header;
    while (p->next != nullptr)
    {
        p = p->next;
    }
    p->next = n;
}

templateT>
void List<T>::insert(int position, T x)
{
    Node<T>* p = header;
    for (int n = 0; n < position && p->next != nullptr; ++n)
    {
        p = p->next;
    }
    Node<T>* t = new Node<T>(x);
    t->next = p->next;
    p->next = t;
}

templateT>
T List<T>::at(int i)
{
    Node<T>* p = header;
    for (int n = 0; n <= i && p->next != nullptr; ++n)
    {
        p = p->next;
    }
    return p->value;
}

templateT>
void List<T>::removeAt(int i)
{
    Node<T>* p = header;
    for (int n = 0; n < i && p->next != nullptr; ++n)
    {
        p = p->next;
    }
    Node<T>* tp = p;
    p = p->next;
    tp->next = p->next;
    delete p;
    p = nullptr;
}

templateT>
inline void List<T>::remove(T x)
{
    Node<T>* p = header;
    while(p->next)
    {
        if (p->next->value == x)
        {
            Node<T>* tp = p;
            p = p->next;
            tp->next = p->next;
            delete p;
            p = nullptr;
            break;
        }
        p = p->next;
    }
}

templateT>
int List<T>::size()const
{
    Node<T>* p = header;
    int n = 0;
    while (p->next != nullptr)
    {
        p = p->next;
        n++;
    }
    return n;
}

#endif // !LIST_DEF_H

main.cpp:

#include 
#include "list.h"

using namespace std;

int main()
{
    List<int> list;
    for (int i = 2; i < 100; i += 2)
        list.append(i);

    for (int i = 0; i < list.size(); ++i)
        cout << list.at(i) << "  ";
    cout << endl;

    List<double> list1;
    for (double i = 2.3; i < 100; i += 2.1)
        list1.append(i);

    for (int i = 0; i < list1.size(); ++i)
        cout << list1.at(i) << "  ";
    cout << endl;
    system("pause");
    return 0;
}

你可能感兴趣的:(数据结构,单链表,C++模板类)