链式存储结构的线性表

/**
 * List.h
 * @Author : MJN
 * @Date   : 2011-10-30
 */

#pragma once

template< class T >
struct Node
{
    T data;
    Node< T > *next;
};

template< class T >
class List
{
public:
    List(void);
    ~List(void);
    int getLength();
    bool isEmpty();
    T getData(int index);
    int getIndex(T t);
    void addData(T t, int index);
    void addData(T t);
    T deleteData(int index);
    void clear();
    void print();
private:
    Node< T > *head;
    int len;    /* length of list */
};

/**
 * head node
 */
template< class T >
List< T >::List(void)
{
    head = new Node< T >;
    head->next = NULL;
    len = 0;
}

template< class T >
List< T >::~List(void)
{
    clear();
    delete head;
}

template< class T >
void List< T >::clear()
{
    Node< T > *p = head->next;
    Node< T > *q = head->next;
    while (q != NULL)
    {
        q = q->next;
        delete p;
        p = q;
    }
    len = 0;
}

template< class T >
int List< T >::getLength()
{
    return len;
}

template< class T >
bool List< T >::isEmpty()
{
    return (len == 0);
}

template< class T >
int List< T >::getIndex(T t)
{
    int index = -1;
    Node< T > *p = head->next;
    for (int i = 0; i < len; i++)
    {
        if (p->data == t)
        {
            index = i;
            break;
        }
    }
    return index;
}

template< class T >
void List< T >::addData(T t, int index)
{
    if (index < 0 || index > len)
    {
        return;
    }
    Node< T > *p = head;
    for (int i = 0; i < index; i++)
    {
        p = p->next;
    }
    /* now, p points to the index-1 th node */
    Node< T > *newNode = new Node< T >;
    newNode->data = t;
    newNode->next = p->next;
    p->next = newNode;
    len++;
}

template< class T >
void List< T >::addData(T t)
{
    addData(t, len);
}

template< class T >
T List< T >::deleteData(int index)
{
    if (index < 0 || index >= len)
    {
        return NULL;
    }
    Node< T > *p = head;
    for (int i = 0; i < index; i++)
    {
        p = p->next;
    }
    Node< T > *deleteNode = p->next;
    T t = deleteNode->data;
    delete deleteNode;
    len--;
    return t;
}

template< class T >
void List< T >::print()
{
    Node< T > *p = head->next;
    cout << "----" << endl;
    while (p)
    {
        cout << p->data << endl;
        p = p->next;
    }
}

你可能感兴趣的:(链式存储结构的线性表)