数据结构-线性表-双向链表

来源:互联网 发布:java 1到100阶乘 编辑:程序博客网 时间:2024/05/17 07:32

贴一个代码

#include <iostream>using namespace std;template<class T>class DsqList{   typedef struct Node    {        T data;        Node *pre;        Node *next;    };    //结构体    private:        Node *first;    public :        //构造、析构函数        DsqList();        DsqList(T a[],int n);        ~DsqList();        //功能函数        //计算链表长度        int Length();        //打印链表        void Print();        //按位查找数据        T GetData(int size);        //按值查找        int GetSize(T data);        //插入元素        void Insert(T data,int size);};template<class T>DsqList<T>::DsqList()   //无参构造{    first = new Node;    first->next = NULL;    first->pre = NULL;}template<class T>DsqList<T>::DsqList(T a[],int n)    //创建链表{    first = new Node;    first->next = NULL;    first->pre = NULL;    Node *p = first;    for(int i = 0;i < n;i ++)    {        Node *newnode = new Node;        newnode->data = a[i];        newnode->pre = p;        first->pre = newnode;        p->next=newnode;        newnode->next = first;        p = newnode;    }}template<class T>DsqList<T>::~DsqList()//析构函数{    Node *p = first->next;    while(p != first)    {        Node *tp = p;        p = p->next;        first->next = p;        p->pre = first;    }    delete(first);}template<class T>int DsqList<T>::Length()    //计算长度{    int len = 0;    Node *p = first;    while(p->next!=first)    {        p=p->next;        len ++;    }    return len;}template<class T>void DsqList<T>::Print()    //打印链表{    Node *p = first;    while(p->next!=first)    {        p=p->next;        cout<<p->data<<" ";    }    cout<<endl;}template<class T>T DsqList<T>::GetData(int size) //查找某个位置数据{    int i = 0;    Node *p = first;    while(p->next!=first)    {        p = p->next;        i ++;        if(size == i)            return p->data;    }    throw "找不到对应值";}template<class T>int DsqList<T>::GetSize(T data)    //查找某个数据位置{    int i = 0;    Node *p = first;    while(p->next!=first)    {        p=p->next;        i ++;        if(p->data == data)                return i;    }    return -1;}template<class T>void DsqList<T>::Insert(T data,int size)    //在某个位置插入数据{    int i = 0;    Node *p = first;    while(p->next!=first)    {        p = p->next;        i ++;        if(i == size)        {            Node *pt = new Node;            pt->data = data;            //创建节点            Node *pr = p->pre;            pt->next = p;            pr->next = pt;            p->pre = pt;            pt->pre = pr;        }    }}int main(){    float a[] = {1.0,2,3,3.3,4,5.21,6};    DsqList<float> ds(a,7);    cout<<"链表长度"<<ds.Length()<<endl;    cout<<"打印链表"<<endl;    ds.Print();    cout<<"查找元素3.3"<<'\t'<<ds.GetSize(3.3)<<endl;    cout<<"查找位置5"<<'\t'<<ds.GetData(5)<<endl;    cout<<"在1号位置和7号位置插入元素后:"<<endl;    ds.Insert(0,1);    ds.Insert(99.99,8);    ds.Print();    return 0;}


原创粉丝点击