码迷,mamicode.com
首页 > 编程语言 > 详细

C++双向循环链表

时间:2015-05-23 14:14:41      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:template   链表   双向循环链表   

#include <iostream>
using namespace std;

template<typename Type>
struct Node
{
    Node<Type> *next;
    Node<Type> *prve;
    Type data;
    Node(Type d = Type()):data(d),next(NULL),prve(NULL){}   
};

template<typename Type>
class DCList
{
    public:
    DCList()
    {
        tail = head = new Node<Type>();
        head->prve = tail;
        tail -> next = head;
    }
    bool Insert(Type a[],int n)
    {
        for(int i=0;i<n;i++)
        {
            _Insert(a[i]);
        }
        return true;
    }
    void Printf(Type d = Type())//从指定节点开始打印,默认从头节点开始。
    {
        Node<Type> *p = head;
        if(d==Type())
        {
            p=p->next;
            while(p!=head)
            {
            cout<<p->data<<"\t";
            p=p->next;
            }
          cout<<endl;
        }
        else if(d<0)
        {
            while(d++)
                p = p->prve;
        }
        else
        {
            while(d--)
                p=p->next;
        }
        while(p!=head)
        {
            cout<<p->data<<"\t";
            p=p->next;
        }
    }
    bool Remove(Type val)
    {
        return _Remove(val);
    }
    bool Empty()
    {
        return _Empty();
    }
    void Find(Type val)
    {
        _Find(val);
    }
    private:
    Node<Type>* _Find(Type val)
    {
        Node<Type> *p = head->next;
        while(p!=head)
        {
            if(p->data == val)
            break;
            p = p->next;
        }
        if(p==head)return NULL;
        else
            return p;
    }
    bool _Empty()
    {
        return head->next == head;
    }
    bool _Remove(Type val)
    {
            Node<Type> *p = head->next;
            p = _Find(val);
         if(p!=NULL)
            {
                p->prve->next = p->next;
                p->next->prve = p->prve;
                delete p;
                p = NULL;
                return true;
            }
            return false;
    }
    bool _Insert(Type val)
    {
        Node<Type> *p = head;
        Node<Type> *s = new Node<Type>(val);
        while(p->next!=head)
        {
            p=p->next;
        }
        p->next = s;
        s->prve = p;
        tail = s;
        tail -> next = head;
        head->prve = tail;
        return true;
    }
    private:
    Node<Type> *head;
    Node<Type> *tail;
};

int main()
{
    DCList<int> list;
    int a[]={2,3,4,5,1};
    list.Insert(a,5);
//  list.Remove(3);
    list.Printf(0);
    return 0;
}

技术分享

C++双向循环链表

标签:template   链表   双向循环链表   

原文地址:http://blog.csdn.net/liuhuiyan_2014/article/details/45933833

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!